promocrypt-cli 1.1.0

Command-line tool for promotional code generation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
# promocrypt

```
                                                       _
 _ __  _ __ ___  _ __ ___   ___   ___ _ __ _   _ _ __ | |_
| '_ \| '__/ _ \| '_ ` _ \ / _ \ / __| '__| | | | '_ \| __|
| |_) | | | (_) | | | | | | (_) | (__| |  | |_| | |_) | |_
| .__/|_|  \___/|_| |_| |_|\___/ \___|_|   \__, | .__/ \__|
|_|                                        |___/|_|
```

[![Release](https://github.com/professor93/promocrypt-cli/actions/workflows/release.yml/badge.svg)](https://github.com/professor93/promocrypt-cli/actions/workflows/release.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

**Command-line tool for cryptographically secure promotional code generation and management.**

Generate millions of unique, validated promotional codes with machine-binding security, database integration, and flexible output formats.

---

## Table of Contents

- [Overview](#overview)
- [Features](#features)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Commands Reference](#commands-reference)
- [Database Integration](#database-integration)
- [Typed Column Values](#typed-column-values)
- [External Commands](#external-commands)
- [Code Formatting](#code-formatting)
- [Check Position](#check-position)
- [Storage Encryption](#storage-encryption)
- [History & Generation Log](#history--generation-log)
- [Secret Rotation](#secret-rotation)
- [Shell Completions](#shell-completions)
- [Environment Variables](#environment-variables)
- [Exit Codes](#exit-codes)
- [Examples](#examples)
- [Building from Source](#building-from-source)
- [License](#license)

---

## Overview

`promocrypt` is a high-performance CLI for generating and managing promotional codes. Built on the `promocrypt-core` cryptographic library, it provides:

- **Cryptographic security**: Codes are generated using secure algorithms with embedded check digits
- **Machine binding**: `.bin` files can be locked to specific machines
- **Database integration**: Direct insertion to PostgreSQL and SQLite
- **Flexible formatting**: Prefixes, suffixes, and separators (e.g., `PROMO-XXXX-XXXX-2024`)
- **Audit trail**: Track generation history, secret rotations, and configuration changes

---

## Features

| Feature | Description |
|---------|-------------|
| **Code Generation** | Generate single codes or millions in batches |
| **Code Validation** | Validate codes from CLI, files, or databases |
| **Database Insert** | PostgreSQL and SQLite with batch insertion |
| **Storage Encryption** | Encrypt codes at rest (AES-256-SIV) |
| **External Commands** | Pipe to any script (Python, Node.js, etc.) |
| **Output Formats** | Plain text, JSON, CSV |
| **Shell Completions** | Bash, Zsh, Fish, PowerShell |
| **Check Position** | Configurable check digit placement |
| **Code Formatting** | Prefix, suffix, separators |
| **Secret Rotation** | Safely change passwords |
| **History Tracking** | Audit rotations, masterings, changes |
| **Generation Log** | Track when/how many codes generated |
| **PG Sync** | Import/export .bin to PostgreSQL |
| **Dry-run Mode** | Preview without generating |
| **Rate Limiting** | Control generation speed |

---

## Installation

### Download from Releases

Download the latest release for your platform:

```bash
# Linux (x86_64)
curl -LO https://github.com/professor93/promocrypt-cli/releases/latest/download/promocrypt-linux-x86_64.tar.gz
tar -xzf promocrypt-linux-x86_64.tar.gz
sudo mv promocrypt /usr/local/bin/

# macOS (Apple Silicon)
curl -LO https://github.com/professor93/promocrypt-cli/releases/latest/download/promocrypt-macos-arm64.tar.gz
tar -xzf promocrypt-macos-arm64.tar.gz
sudo mv promocrypt /usr/local/bin/
```

### Build from Source

```bash
# Clone the repository
git clone https://github.com/professor93/promocrypt-cli.git
cd promocrypt-cli

# Build release binary
cargo build --release

# Install to PATH
sudo cp target/release/promocrypt /usr/local/bin/
```

---

## Quick Start

### 1. Create a .bin file

```bash
# Create a new .bin file with default settings
promocrypt create --name production --secret "my-secure-password"

# Create with custom formatting
promocrypt create --name promo2024 \
    --secret "password" \
    --prefix "PROMO-" \
    --suffix "-2024" \
    --separator "-" \
    --separator-positions "4,8"
```

### 2. Generate codes

```bash
# Generate a single code
promocrypt generate --secret "my-secure-password"

# Generate 1000 codes to file
promocrypt generate --secret "password" -n 1000 -o codes.txt

# Generate with database insertion
promocrypt generate --secret "password" -n 10000 --db db.toml --table promos
```

### 3. Validate codes

```bash
# Validate a single code
promocrypt validate PROMO-A3KF-7NP2-2024

# Validate from file
promocrypt validate -f codes.txt --summary

# Validate with quiet mode (only show invalid)
promocrypt validate -f codes.txt --quiet
```

---

## Commands Reference

### Global Options

```
promocrypt [OPTIONS] <COMMAND>

Options:
    --bin <PATH>           Path to .bin file (default: ./promocrypt.bin)
    --format <FORMAT>      Output format: plain, json, csv (default: plain)
    --quiet                Suppress non-essential output
    --env-file <PATH>      Load environment from file
    -h, --help             Print help
    -V, --version          Print version
```

### create

Create a new .bin file.

```bash
promocrypt create [OPTIONS]

Options:
    --name <NAME>                  Secret name (required)
    --secret <SECRET>              Secret password (prompted if not provided)
    --alphabet <ALPHABET>          Custom alphabet (default: 0234679ABCDEFGHJKMNPQRTUXY)
    --length <N>                   Code length excluding check (default: 9)
    --check-position <POS>         Check digit position: 0=start, -1=end, N=position
    --counter-mode <MODE>          Counter mode: file, inbin, manual (default: file)
    --counter-path <PATH>          Path for counter file
    --force                        Overwrite if exists
    --prefix <PREFIX>              Prefix for generated codes
    --suffix <SUFFIX>              Suffix for generated codes
    --separator <CHAR>             Separator character (e.g., '-')
    --separator-positions <POS>    Comma-separated positions (e.g., "4,8")
    --storage-encryption           Enable storage encryption for codes

Examples:
    # Basic
    promocrypt create --name prod --secret "password"

    # With formatting
    promocrypt create --name promo --secret "pass" \
        --prefix "SALE-" --separator "-" --separator-positions "4,8"

    # With storage encryption
    promocrypt create --name secure --secret "pass" --storage-encryption
```

### info

Show .bin file information.

```bash
promocrypt info [OPTIONS]

Options:
    --show-audit           Show audit trail details
    --show-history         Show history (rotations, masterings, changes)
    --show-generation-log  Show generation log
    --show-machine-id      Show current machine ID
    --json                 Output as JSON

Examples:
    promocrypt info
    promocrypt info --show-history --json
    promocrypt info --show-machine-id
```

### generate

Generate promotional codes.

```bash
promocrypt generate [OPTIONS]

Options:
    --secret <SECRET>              Secret password
    -n, --count <N>                Number of codes (default: 1)
    -c, --counter <N>              Manual counter value
    -o, --output <FILE>            Output file (default: stdout)
    --chunk-size <N>               Chunk size for batches (default: 10000)
    --dry-run                      Preview without generating
    --rate-limit <N>               Max codes per second (0 = unlimited)

    # Format options (override .bin config)
    --prefix <PREFIX>              Add prefix to codes
    --suffix <SUFFIX>              Add suffix to codes
    --separator <CHAR>             Separator character
    --separator-positions <POS>    Separator positions

    # Database options
    --db <CONFIG>                  Database config file (TOML)
    --table <TABLE>                Target table name
    --column <COLUMN>              Code column name (default: code)
    --retry-duplicates             Auto-retry on duplicate key conflict

    # Typed column values
    --set <KEY=VALUE>              Set string column
    --set-int <KEY=VALUE>          Set integer column
    --set-float <KEY=VALUE>        Set float column
    --set-bool <KEY=VALUE>         Set boolean column
    --set-now <KEY>                Set column to current timestamp
    --set-json <KEY=VALUE>         Set JSON/JSONB column
    --set-null <KEY>               Set column to NULL
    --extra <JSON>                 Extra columns as JSON

    # External command
    --exec <COMMAND>               Pipe codes to external command
    --exec-format <FMT>            Format: plain, jsonl (default: plain)

Examples:
    # Generate to stdout
    promocrypt generate --secret pass -n 10

    # Generate to file
    promocrypt generate --secret pass -n 1000 -o codes.txt

    # Generate with database
    promocrypt generate --secret pass -n 10000 --db db.toml --table promos \
        --set-int campaign_id=123 --set status=active --set-now created_at

    # Dry run
    promocrypt generate --secret pass -n 10 --dry-run
```

### validate

Validate promotional codes.

```bash
promocrypt validate [OPTIONS] [CODE]

Arguments:
    [CODE]                 Single code to validate

Options:
    -f, --file <FILE>      File with codes (one per line)
    --from-db              Validate all codes in database table
    --db <CONFIG>          Database config (for --from-db)
    --table <TABLE>        Table to read codes from
    --column <COLUMN>      Code column name (default: code)
    --quiet                Only output invalid codes
    --summary              Show summary at end

Examples:
    promocrypt validate A3KF7NP2XM
    promocrypt validate -f codes.txt --summary
    promocrypt validate --from-db --db db.toml --table promos
```

### lookup

Look up code status in database.

```bash
promocrypt lookup [OPTIONS] <CODE>

Arguments:
    <CODE>                 Code to look up

Options:
    --db <CONFIG>          Database config file (required)
    --table <TABLE>        Table name (required)
    --column <COLUMN>      Code column name (default: code)

Example:
    promocrypt lookup PROMO-A3KF7NP2XM-2024 --db db.toml --table promos
```

### stats

Show statistics about .bin file and database.

```bash
promocrypt stats [OPTIONS]

Options:
    --db <CONFIG>          Include database statistics
    --table <TABLE>        Table to count codes in

Examples:
    promocrypt stats
    promocrypt stats --db db.toml --table promos
```

### export

Export codes from database.

```bash
promocrypt export [OPTIONS]

Options:
    --db <CONFIG>              Database config (required)
    --table <TABLE>            Table name (required)
    --column <COLUMN>          Code column name (default: code)
    -o, --output <FILE>        Output file (required)
    --export-format <FMT>      Format: csv, json, sql (default: csv)
    --where <CONDITION>        SQL WHERE clause
    --limit <N>                Maximum rows to export

Examples:
    promocrypt export --db db.toml --table promos -o codes.csv
    promocrypt export --db db.toml --table promos -o unused.json \
        --export-format json --where "used_at IS NULL"
```

### master

Master .bin for a different machine.

```bash
promocrypt master [OPTIONS]

Options:
    --secret <SECRET>          Secret password
    --output <PATH>            Output path for mastered .bin
    --target-machine <HEX>     Target machine ID (hex)
    --show-machine-id          Show machine ID and exit

Examples:
    # Get your machine ID
    promocrypt master --show-machine-id

    # Master for another machine
    promocrypt master --secret pass --output server.bin \
        --target-machine a1b2c3d4e5f6...
```

### config

View or modify .bin configuration.

```bash
promocrypt config [OPTIONS]

Options:
    --secret <SECRET>                  Secret password (required for modifications)
    --show                             Show current configuration
    --set-prefix <PREFIX>              Set prefix (empty string to remove)
    --set-suffix <SUFFIX>              Set suffix (empty string to remove)
    --set-separator <CHAR>             Set separator character
    --set-separator-positions <POS>    Set separator positions
    --set-check-position <N>           Set check position index
    --set-storage-encryption <BOOL>    Enable/disable storage encryption

Examples:
    promocrypt config --show
    promocrypt config --secret pass --set-prefix "NEW-"
    promocrypt config --secret pass --set-storage-encryption true
```

### rotate-secret

Rotate secret password.

```bash
promocrypt rotate-secret [OPTIONS]

Options:
    --old-secret <SECRET>      Current secret
    --new-secret <SECRET>      New secret (prompted if not provided)

Example:
    promocrypt rotate-secret --old-secret "old-pass" --new-secret "new-pass"
```

### history

View, export, or clear history.

```bash
promocrypt history [OPTIONS]

Options:
    --export <FILE>            Export history to JSON file
    --clear                    Clear history (requires --secret)
    --keep-last <N>            Keep last N entries when clearing
    --secret <SECRET>          Required for --clear

Examples:
    promocrypt history
    promocrypt history --export history.json
    promocrypt history --clear --keep-last 10 --secret pass
```

### generation-log

View, export, or clear generation log.

```bash
promocrypt generation-log [OPTIONS]

Options:
    --export <FILE>            Export log to JSON file
    --clear                    Clear log (requires --secret)
    --keep-last <N>            Keep last N entries when clearing
    --secret <SECRET>          Required for --clear
    --summary                  Show summary only

Examples:
    promocrypt generation-log
    promocrypt generation-log --summary
    promocrypt generation-log --export gen-log.json
```

### pg-import

Import .bin file into PostgreSQL.

```bash
promocrypt pg-import [OPTIONS]

Options:
    --db <CONFIG>              PostgreSQL config file (required)
    --secret <SECRET>          Secret password (required)
    --name <NAME>              Name in PostgreSQL (default: use .bin name)

Example:
    promocrypt pg-import --db pg.toml --secret pass
```

### pg-export

Export .bin from PostgreSQL to file.

```bash
promocrypt pg-export [OPTIONS]

Options:
    --db <CONFIG>              PostgreSQL config file (required)
    --name <NAME>              Secret name in PostgreSQL (required)
    --secret <SECRET>          Secret password (required)
    -o, --output <PATH>        Output .bin file path (required)

Example:
    promocrypt pg-export --db pg.toml --name campaign --secret pass -o campaign.bin
```

### completions

Generate shell completions.

```bash
promocrypt completions <SHELL>

Arguments:
    <SHELL>    Shell: bash, zsh, fish, powershell, elvish

Example:
    promocrypt completions bash > ~/.local/share/bash-completion/completions/promocrypt
```

---

## Database Integration

### PostgreSQL Setup

1. Create a database config file:

```toml
# db-postgres.toml
[database]
type = "postgresql"
host = "localhost"
port = 5432
database = "mydb"
user = "user"
password = "password"
# OR use connection string:
# connection_string = "postgres://user:pass@localhost/mydb"

[insert]
table = "promo_codes"
code_column = "code"

[insert.extra]
campaign_id = 123
status = "active"
```

2. Create the table:

```sql
CREATE TABLE promo_codes (
    id SERIAL PRIMARY KEY,
    code VARCHAR(50) UNIQUE NOT NULL,
    campaign_id INTEGER,
    status VARCHAR(20) DEFAULT 'active',
    used_at TIMESTAMP,
    created_at TIMESTAMP DEFAULT NOW()
);
```

3. Generate codes:

```bash
promocrypt generate --secret pass -n 10000 --db db-postgres.toml
```

### SQLite Setup

1. Create a database config file:

```toml
# db-sqlite.toml
[database]
type = "sqlite"
path = "./codes.db"

[insert]
table = "promo_codes"
code_column = "code"
```

2. Create the database:

```bash
sqlite3 codes.db "CREATE TABLE promo_codes (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    code TEXT UNIQUE NOT NULL,
    campaign_id INTEGER,
    status TEXT DEFAULT 'active',
    used_at TEXT,
    created_at TEXT DEFAULT CURRENT_TIMESTAMP
);"
```

3. Generate codes:

```bash
promocrypt generate --secret pass -n 10000 --db db-sqlite.toml
```

---

## Typed Column Values

Set column values with proper types during generation:

| Option | Type | Example |
|--------|------|---------|
| `--set` | String | `--set status=active` |
| `--set-int` | Integer | `--set-int campaign_id=123` |
| `--set-float` | Float | `--set-float discount=19.99` |
| `--set-bool` | Boolean | `--set-bool single_use=true` |
| `--set-now` | Timestamp | `--set-now created_at` |
| `--set-json` | JSON/JSONB | `--set-json meta='{"source":"cli"}'` |
| `--set-null` | NULL | `--set-null deleted_at` |

**Priority:** `--set-*` > `--extra` > config file

**Example:**

```bash
promocrypt generate --secret pass -n 1000 --db db.toml --table promos \
    --set-int campaign_id=123 \
    --set-int discount=20 \
    --set status=active \
    --set-bool single_use=true \
    --set-now created_at \
    --set-json metadata='{"source": "cli", "version": 1}'
```

---

## External Commands

Pipe codes to any external program for custom database insertion:

```bash
# Plain text (one code per line)
promocrypt generate --secret pass -n 10000 --exec "./my-inserter.sh"

# JSON lines with extra data
promocrypt generate --secret pass -n 10000 \
    --exec "python insert.py" \
    --exec-format jsonl \
    --set-int campaign_id=123
```

### Example Scripts

**Bash + psql (PostgreSQL):**

```bash
#!/bin/bash
while read code; do
    psql -c "INSERT INTO promos (code) VALUES ('$code')"
done
```

**Python + MongoDB:**

```python
#!/usr/bin/env python3
import sys
from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017')
db = client.mydb

for line in sys.stdin:
    code = line.strip()
    db.promos.insert_one({"code": code})
```

**Node.js + MySQL:**

```javascript
#!/usr/bin/env node
const mysql = require('mysql2/promise');
const readline = require('readline');

async function main() {
    const conn = await mysql.createConnection({
        host: 'localhost', user: 'root', database: 'mydb'
    });
    const rl = readline.createInterface({ input: process.stdin });

    for await (const code of rl) {
        await conn.execute(
            'INSERT INTO promos (code) VALUES (?)',
            [code.trim()]
        );
    }
    await conn.end();
}
main();
```

---

## Code Formatting

### Prefix and Suffix

```bash
# Set during creation (stored in .bin)
promocrypt create --name promo --secret pass \
    --prefix "PROMO-" --suffix "-2024"

# Override during generation
promocrypt generate --secret pass -n 10 --prefix "SALE-" --suffix ""

# Output: PROMO-A3KF7NP2XM-2024
```

### Separators

```bash
# Create with separators at positions 4 and 8
promocrypt create --name readable --secret pass \
    --separator "-" --separator-positions "4,8"

# Output: XXXX-XXXX-XX
```

---

## Check Position

The check digit position can be configured for security:

| Value | Meaning | Example (10-char) |
|-------|---------|-------------------|
| `-1` | End (default) | `XXXXXXXXX[C]` |
| `0` | Start | `[C]XXXXXXXXX` |
| `4` | Position 4 | `XXXX[C]XXXXX` |
| `-3` | 3rd from end | `XXXXXXX[C]XX` |

**Security benefit:** Attackers don't know where the check digit is located.

```bash
promocrypt create --name secure --secret pass --check-position 4
```

---

## Storage Encryption

Enable storage encryption for codes stored in SQLite (desktop apps):

```bash
# Enable during creation
promocrypt create --name desktop --secret pass --storage-encryption

# Toggle on existing .bin
promocrypt config --secret pass --set-storage-encryption true
```

**Algorithm:** AES-256-SIV (deterministic, allows lookups)

---

## History & Generation Log

### View History

```bash
# View all history
promocrypt history

# Export to JSON
promocrypt history --export history.json

# Clear (keep last 10)
promocrypt history --clear --keep-last 10 --secret pass
```

### View Generation Log

```bash
# View log
promocrypt generation-log

# View summary
promocrypt generation-log --summary

# Export to JSON
promocrypt generation-log --export gen-log.json
```

---

## Secret Rotation

Safely rotate the secret password:

```bash
promocrypt rotate-secret --old-secret "old-password" --new-secret "new-password"
```

After rotation:
- All future operations require the new secret
- The change is logged in history

---

## Shell Completions

### Bash

```bash
promocrypt completions bash > ~/.local/share/bash-completion/completions/promocrypt
# Or system-wide:
sudo promocrypt completions bash > /etc/bash_completion.d/promocrypt
```

### Zsh

```bash
promocrypt completions zsh > ~/.zsh/completions/_promocrypt
# Add to .zshrc:
fpath=(~/.zsh/completions $fpath)
autoload -Uz compinit && compinit
```

### Fish

```bash
promocrypt completions fish > ~/.config/fish/completions/promocrypt.fish
```

### PowerShell

```powershell
promocrypt completions powershell >> $PROFILE
```

---

## Environment Variables

| Variable | Description |
|----------|-------------|
| `PROMOCRYPT_SECRET` | Default secret password |
| `PROMOCRYPT_BIN` | Default .bin file path |
| `DATABASE_URL` | Database connection string |

**Example:**

```bash
export PROMOCRYPT_SECRET="my-secret"
export PROMOCRYPT_BIN="./production.bin"

# No need to specify --secret or --bin
promocrypt generate -n 100
```

---

## Exit Codes

| Code | Meaning |
|------|---------|
| 0 | Success |
| 1 | Validation failed (some codes invalid) |
| 2 | File/path error |
| 3 | Authentication error (wrong secret/machine) |
| 4 | Database error |
| 5 | Configuration error |
| 6 | External command error |
| 7 | Code not found (lookup) |

---

## Examples

### Campaign Launch

```bash
# Create a campaign-specific .bin
promocrypt create --name summer2024 --secret "secure-pass" \
    --prefix "SUMMER24-" \
    --separator "-" --separator-positions "4,8"

# Generate 100,000 codes to database
promocrypt generate --secret "secure-pass" -n 100000 \
    --db db.toml --table summer_promos \
    --set-int campaign_id=42 \
    --set-int discount=25 \
    --set-now created_at
```

### Multi-Machine Deployment

```bash
# On development machine
promocrypt master --show-machine-id
# Output: a1b2c3d4e5f6...

# Get production server's machine ID
ssh prod-server "promocrypt master --show-machine-id"
# Output: f6e5d4c3b2a1...

# Master the .bin for production
promocrypt master --secret "pass" \
    --output prod.bin \
    --target-machine f6e5d4c3b2a1...

# Copy to production
scp prod.bin prod-server:/app/
```

### Bulk Validation

```bash
# Validate codes from file
promocrypt validate -f codes.txt --summary

# Validate all codes in database
promocrypt validate --from-db --db db.toml --table promos --summary
```

### Export Unused Codes

```bash
# Export unused codes to CSV
promocrypt export --db db.toml --table promos \
    -o unused_codes.csv \
    --where "used_at IS NULL"

# Export as SQL for migration
promocrypt export --db db.toml --table promos \
    -o migrate.sql \
    --export-format sql
```

---

## Building from Source

### Requirements

- Rust 1.89.0+
- OpenSSL development libraries (Linux)

### Build

```bash
git clone https://github.com/professor93/promocrypt-cli.git
cd promocrypt-cli

# Debug build
cargo build

# Release build
cargo build --release

# Run tests
cargo test
```

### Cross-compilation

```bash
# For Linux from macOS
rustup target add x86_64-unknown-linux-gnu
cargo build --release --target x86_64-unknown-linux-gnu
```

---

## License

MIT License - see [LICENSE](LICENSE) for details.

---

**Made with Rust**