forked from larrychristensen/orcpub
-
-
Notifications
You must be signed in to change notification settings - Fork 114
Expand file tree
/
Copy pathrun
More file actions
executable file
·1566 lines (1370 loc) · 53.8 KB
/
run
File metadata and controls
executable file
·1566 lines (1370 loc) · 53.8 KB
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
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
#
# OrcPub / Dungeon Master's Vault — Docker Setup Script
#
# Prepares everything needed to run the application via Docker Compose:
# 1. Generates secure random passwords and a signing secret
# 2. Creates a .env file (or uses an existing one)
# 3. Generates self-signed SSL certificates (if missing)
# 4. Creates required directories (data, logs, deploy/homebrew)
#
# Usage:
# ./${SCRIPT_NAME} # Interactive mode — prompts for optional values
# ./${SCRIPT_NAME} --auto # Non-interactive — accepts all defaults
# ./${SCRIPT_NAME} --help # Show usage
#
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SCRIPT_NAME="$(basename "${BASH_SOURCE[0]}")"
ENV_FILE="${SCRIPT_DIR}/.env"
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
color_green=$'\033[0;32m'
color_yellow=$'\033[1;33m'
color_red=$'\033[0;31m'
color_cyan=$'\033[0;36m'
color_magenta=$'\033[0;35m'
color_reset=$'\033[0m'
info() { printf '%s[INFO]%s %s\n' "$color_green" "$color_reset" "$*"; }
warn() { printf '%s[WARN]%s %s\n' "$color_yellow" "$color_reset" "$*"; }
change() { printf '%s[FIXD]%s %s\n' "$color_magenta" "$color_reset" "$*"; }
error() { printf '%s[ERROR]%s %s\n' "$color_red" "$color_reset" "$*" >&2; }
success() { printf '\n%s=== %s ===%s\n' "$color_green" "$*" "$color_reset"; }
header() { printf '\n%s=== %s ===%s\n\n' "$color_cyan" "$*" "$color_reset"; }
next() { printf '%s ▸%s %s\n' "$color_cyan" "$color_reset" "$*"; }
# Read a variable value from a .env file, stripping Windows \r line endings.
# Usage: val=$(read_env_val "VAR_NAME" "/path/to/.env")
read_env_val() {
grep -m1 "^${1}=" "$2" 2>/dev/null | cut -d= -f2- | tr -d '\r' || true
}
# Source a .env file safely (strips Windows \r line endings).
# Usage: source_env "/path/to/.env"
source_env() {
# shellcheck disable=SC1090
. <(tr -d '\r' < "$1")
}
# Set a variable in a .env file. Uses awk to avoid sed delimiter issues with URLs.
# Usage: set_env_val "VAR_NAME" "value" "/path/to/.env"
set_env_val() {
local var="$1" val="$2" file="$3"
if grep -q "^${var}=" "$file" 2>/dev/null; then
awk -v var="$var" -v val="$val" '{
if (index($0, var"=") == 1) print var"="val; else print
}' "$file" > "${file}.tmp"
mv "${file}.tmp" "$file"
else
echo "${var}=${val}" >> "$file"
fi
}
generate_password() {
# Generate a URL-safe random password (no special chars that break URLs/YAML)
local length="${1:-24}"
if command -v openssl &>/dev/null; then
openssl rand -base64 "$((length * 2))" | tr -d '/+=' | head -c "$length"
elif [ -r /dev/urandom ]; then
tr -dc 'A-Za-z0-9' < /dev/urandom | head -c "$length"
else
error "Cannot generate random password: no openssl or /dev/urandom available"
exit 1
fi
}
# Generate docker-compose.secrets.yaml and wire COMPOSE_FILE into .env.
# Usage: write_compose_secrets "file" → file-based secrets
# write_compose_secrets "external" → Swarm external secrets
write_compose_secrets() {
local mode="$1" # "file" or "external"
local secrets_compose="${SCRIPT_DIR}/docker-compose.secrets.yaml"
local compose_file_var="docker-compose.yaml:docker-compose.secrets.yaml"
if [ -f "$secrets_compose" ] && [ "$FORCE_MODE" = "false" ]; then
warn "docker-compose.secrets.yaml already exists. Use --force to overwrite."
return 0
fi
if [ "$mode" = "file" ]; then
cat > "$secrets_compose" <<YAML
# Generated by ./${SCRIPT_NAME} --secrets
# Compose merges this with docker-compose.yaml automatically via COMPOSE_FILE.
secrets:
datomic_password:
file: ./secrets/datomic_password
admin_password:
file: ./secrets/admin_password
signature:
file: ./secrets/signature
services:
orcpub:
secrets:
- datomic_password
- signature
datomic:
secrets:
- datomic_password
- admin_password
YAML
else
cat > "$secrets_compose" <<YAML
# Generated by ./${SCRIPT_NAME} --swarm
# Compose merges this with docker-compose.yaml automatically via COMPOSE_FILE.
secrets:
datomic_password:
external: true
admin_password:
external: true
signature:
external: true
services:
orcpub:
secrets:
- datomic_password
- signature
datomic:
secrets:
- datomic_password
- admin_password
YAML
fi
change "Created docker-compose.secrets.yaml"
# Add COMPOSE_FILE to .env so compose merges both files automatically
if [ -f "$ENV_FILE" ]; then
local current_cf
current_cf=$(read_env_val COMPOSE_FILE "$ENV_FILE")
if [ -z "$current_cf" ]; then
{
echo ""
echo "# --- Compose file merge (secrets) ---"
echo "COMPOSE_FILE=${compose_file_var}"
} >> "$ENV_FILE"
change "Added COMPOSE_FILE to .env (compose will merge both files)"
elif [ "$current_cf" != "$compose_file_var" ]; then
warn "COMPOSE_FILE already set in .env: ${current_cf}"
warn "Make sure it includes docker-compose.secrets.yaml"
fi
else
warn "No .env file — add to your environment:"
warn " export COMPOSE_FILE=${compose_file_var}"
fi
}
# Switch transactor host binding between Compose and Swarm modes.
# Usage: switch_transactor_host "compose" → host=datomic (Compose DNS bind)
# switch_transactor_host "swarm" → host=0.0.0.0 (Swarm all-interfaces)
switch_transactor_host() {
local mode="$1"
local template="${SCRIPT_DIR}/docker/transactor.properties.template"
[ -f "$template" ] || return 0
if [ "$mode" = "compose" ]; then
if grep -q '^host=0\.0\.0\.0' "$template"; then
sed -i 's/^host=0\.0\.0\.0$/#host=0.0.0.0/' "$template"
sed -i 's/^#host=datomic$/host=datomic/' "$template"
change "Transactor host: 0.0.0.0 → datomic (Compose bind)"
fi
elif [ "$mode" = "swarm" ]; then
if grep -q '^host=datomic' "$template"; then
sed -i 's/^host=datomic$/#host=datomic/' "$template"
sed -i 's/^#host=0\.0\.0\.0$/host=0.0.0.0/' "$template"
change "Transactor host: datomic → 0.0.0.0 (Swarm bind)"
fi
fi
}
# Read DATOMIC_PASSWORD, ADMIN_PASSWORD, SIGNATURE from .env + shell env.
# Sets _pw_datomic, _pw_admin, _pw_signature. Exits on missing values.
# Usage: read_passwords "--secrets" (label for error message)
read_passwords() {
local mode_label="$1"
_pw_datomic=""
_pw_admin=""
_pw_signature=""
if [ -f "$ENV_FILE" ]; then
info "Reading passwords from .env"
_pw_datomic=$(read_env_val DATOMIC_PASSWORD "$ENV_FILE")
_pw_admin=$(read_env_val ADMIN_PASSWORD "$ENV_FILE")
_pw_signature=$(read_env_val SIGNATURE "$ENV_FILE")
fi
# Fill gaps from shell env vars (for admins who export directly)
_pw_datomic="${_pw_datomic:-${DATOMIC_PASSWORD:-}}"
_pw_admin="${_pw_admin:-${ADMIN_PASSWORD:-}}"
_pw_signature="${_pw_signature:-${SIGNATURE:-}}"
if [ -z "$_pw_datomic" ] || [ -z "$_pw_admin" ] || [ -z "$_pw_signature" ]; then
error "Could not find all required passwords."
error "Checked .env file and shell environment variables."
[ -z "$_pw_datomic" ] && error " DATOMIC_PASSWORD — not found"
[ -z "$_pw_admin" ] && error " ADMIN_PASSWORD — not found"
[ -z "$_pw_signature" ] && error " SIGNATURE — not found"
echo ""
error "Either create a .env file (./${SCRIPT_NAME}) or export the"
error "variables in your shell before running ${mode_label}."
exit 1
fi
}
# Check that a file exists, incrementing ERRORS if not.
# Usage: check_file "label" "/path/to/file"
check_file() {
local label="$1" path="$2"
if [ -f "$path" ]; then
info " ${label}: OK"
else
warn " ${label}: MISSING"
WARNING_MSGS+=("${label} is missing")
ERRORS=$((ERRORS + 1))
fi
}
# Check that a directory exists, incrementing ERRORS if not.
# Usage: check_dir "label" "/path/to/dir"
check_dir() {
local label="$1" path="$2"
if [ -d "$path" ]; then
info " ${label}: OK"
else
warn " ${label}: MISSING"
WARNING_MSGS+=("${label} is missing")
ERRORS=$((ERRORS + 1))
fi
}
# Check if a shell env var conflicts with .env value, incrementing ERRORS if so.
# Usage: check_env_conflict "VAR_NAME"
check_env_conflict() {
local var_name="$1"
local env_val="${!var_name:-}"
local file_val
file_val=$(read_env_val "$var_name" "$ENV_FILE")
if [ -n "$env_val" ] && [ -n "$file_val" ] && [ "$env_val" != "$file_val" ]; then
warn " Shell \$${var_name} differs from .env value"
warn " Shell: ${env_val}"
warn " .env: ${file_val}"
ENV_CONFLICTS+=("$var_name")
WARNING_MSGS+=("\$${var_name}: shell value overrides .env")
ERRORS=$((ERRORS + 1))
fi
}
# Build a docker compose command, prefixing with env -u for each shell/env conflict.
# Usage: build_compose_cmd "docker compose up --build -d"
build_compose_cmd() {
local base_cmd="$1"
if [ "${#ENV_CONFLICTS[@]}" -gt 0 ]; then
local prefix=""
for var in "${ENV_CONFLICTS[@]}"; do
prefix="${prefix}env -u ${var} "
done
echo "${prefix}${base_cmd}"
else
echo "$base_cmd"
fi
}
prompt_value() {
local prompt_text="$1"
local default_value="$2"
local result
if [ "${AUTO_MODE:-false}" = "true" ]; then
echo "$default_value"
return
fi
if [ -n "$default_value" ]; then
read -rp "${prompt_text} [${default_value}]: " result || true
echo "${result:-$default_value}"
else
read -rp "${prompt_text}: " result || true
echo "$result"
fi
}
# Confirm an action, auto-accepting in auto mode.
# Returns 0 (yes) or 1 (no). Usage:
# if confirm_action "Stop Compose services now?"; then ...
confirm_action() {
local prompt_text="$1"
if [ "${AUTO_MODE:-false}" = "true" ]; then
return 0
fi
local _answer
read -rp "${prompt_text} [Y/n]: " _answer || true
[[ "${_answer,,}" =~ ^(y|)$ ]]
}
# Write .env file using current variable values.
# Expects PORT, ADMIN_PASSWORD, DATOMIC_PASSWORD, SIGNATURE, EMAIL_*, ORCPUB_IMAGE,
# DATOMIC_IMAGE, INIT_ADMIN_* to be set in scope before calling.
write_env_file() {
cat > "$ENV_FILE" <<EOF
# ============================================================================
# Dungeon Master's Vault — Docker Environment Configuration
# Generated by run on $(date -u +"%Y-%m-%d %H:%M:%S UTC")
# ============================================================================
# --- Application ---
PORT=${PORT}
# --- Docker Images ---
# Set these to version your builds (e.g. orcpub-app:v2.6.0)
# Leave empty to use default names (orcpub-app, orcpub-datomic)
ORCPUB_IMAGE=${ORCPUB_IMAGE}
DATOMIC_IMAGE=${DATOMIC_IMAGE}
# --- Datomic Database ---
# ADMIN_PASSWORD — internal storage admin. Controls who can create/delete
# databases on the transactor. Only the transactor uses it; the app never sees it.
# DATOMIC_PASSWORD — peer connection password. The transactor and app must share
# the same value. The app appends it to DATOMIC_URL at startup automatically.
#
# WARNING: Both passwords are locked into the database on first startup.
# Changing them later will prevent the transactor from starting (ADMIN_PASSWORD)
# or the app from connecting (DATOMIC_PASSWORD). Your data is NOT lost — set
# the password back, or use the _OLD vars below for graceful rotation.
ADMIN_PASSWORD=${ADMIN_PASSWORD}
DATOMIC_PASSWORD=${DATOMIC_PASSWORD}
DATOMIC_URL=datomic:dev://datomic:4334/orcpub
# --- Transactor Tuning ---
# These rarely need changing. See docker/transactor.properties.template.
ALT_HOST=127.0.0.1
ENCRYPT_CHANNEL=true
# Password rotation: set the OLD var to the previous password, then change the
# main var above. The transactor accepts both during the transition. Remove the
# OLD var after restarting and confirming everything works.
# ADMIN_PASSWORD_OLD=
# DATOMIC_PASSWORD_OLD=
# --- Security ---
# Secret used to sign JWT tokens (20+ characters recommended)
SIGNATURE=${SIGNATURE}
# --- Email (SMTP) ---
EMAIL_SERVER_URL=${EMAIL_SERVER_URL}
EMAIL_ACCESS_KEY=${EMAIL_ACCESS_KEY}
EMAIL_SECRET_KEY=${EMAIL_SECRET_KEY}
EMAIL_SERVER_PORT=${EMAIL_SERVER_PORT}
EMAIL_FROM_ADDRESS=${EMAIL_FROM_ADDRESS}
EMAIL_ERRORS_TO=${EMAIL_ERRORS_TO}
EMAIL_SSL=${EMAIL_SSL}
EMAIL_TLS=${EMAIL_TLS}
# --- SSL (Nginx) ---
# Set to 'true' after running snakeoil.sh or providing your own certs
# SSL_CERT_PATH=./deploy/snakeoil.crt
# SSL_KEY_PATH=./deploy/snakeoil.key
# --- Initial Admin User (optional) ---
# Set these to create an admin account on first run:
# ./docker-user.sh init
# Safe to run multiple times — duplicates are skipped.
INIT_ADMIN_USER=${INIT_ADMIN_USER}
INIT_ADMIN_EMAIL=${INIT_ADMIN_EMAIL}
INIT_ADMIN_PASSWORD=${INIT_ADMIN_PASSWORD}
EOF
chmod 600 "$ENV_FILE"
change ".env file created at ${ENV_FILE} (permissions: 600)"
}
# Create required directories if they don't exist.
setup_directories() {
for dir in "${SCRIPT_DIR}/data" "${SCRIPT_DIR}/logs" "${SCRIPT_DIR}/backups" "${SCRIPT_DIR}/deploy/homebrew"; do
if [ ! -d "$dir" ]; then
mkdir -p "$dir"
change "Created directory: ${dir#"${SCRIPT_DIR}"/}"
else
info "Directory exists: ${dir#"${SCRIPT_DIR}"/}"
fi
done
}
# Generate self-signed SSL certificate if none exists.
setup_ssl_certs() {
local cert="${SCRIPT_DIR}/deploy/snakeoil.crt"
local key="${SCRIPT_DIR}/deploy/snakeoil.key"
if [ -f "$cert" ] && [ -f "$key" ]; then
info "SSL certificates already exist. Skipping generation."
elif command -v openssl &>/dev/null; then
info "Generating self-signed SSL certificate..."
openssl req \
-subj "/C=US/ST=State/L=City/O=OrcPub/OU=Dev/CN=localhost" \
-x509 -nodes -days 365 -newkey rsa:2048 \
-keyout "$key" -out "$cert" 2>/dev/null
change "SSL certificate generated (valid for 365 days)."
else
warn "openssl not found — cannot generate SSL certificates."
warn "Install openssl and run: ./deploy/snakeoil.sh"
fi
}
# Generate a fresh .env through prompts (interactive) or defaults (--auto).
# Also creates directories and SSL certs. Works in both modes because
# prompt_value() returns the default silently when AUTO_MODE=true.
generate_env() {
header "Database Passwords"
DEFAULT_ADMIN_PW="$(generate_password 24)"
DEFAULT_DATOMIC_PW="$(generate_password 24)"
DEFAULT_SIGNATURE="$(generate_password 32)"
echo ""
echo " Datomic uses two passwords (both locked into the DB on first startup):"
echo " Admin password — internal, controls database create/delete"
echo " Peer password — shared between transactor and app for connections"
if [ -f "${SCRIPT_DIR}/data/db/datomic.mv.db" ]; then
echo ""
warn "Existing database found in data/db/."
warn "The admin password is locked into this database. If you set a new"
warn "password, the transactor will fail to start. Either:"
warn " 1. Keep the same admin password as before"
warn " 2. Wipe the database first: rm -rf data/db/*"
fi
echo ""
ADMIN_PASSWORD=$(prompt_value "Admin password" "$DEFAULT_ADMIN_PW")
DATOMIC_PASSWORD=$(prompt_value "Peer password" "$DEFAULT_DATOMIC_PW")
SIGNATURE=$(prompt_value "JWT signing secret (20+ chars)" "$DEFAULT_SIGNATURE")
header "Application"
PORT=$(prompt_value "Application port" "8890")
_image_tag=$(prompt_value "Image tag (leave empty for default)" "")
if [ -n "$_image_tag" ]; then
ORCPUB_IMAGE="orcpub-app:${_image_tag}"
DATOMIC_IMAGE="orcpub-datomic:${_image_tag}"
else
ORCPUB_IMAGE=""
DATOMIC_IMAGE=""
fi
EMAIL_SERVER_URL=$(prompt_value "SMTP server URL (leave empty to skip email)" "")
EMAIL_ACCESS_KEY=""
EMAIL_SECRET_KEY=""
EMAIL_SERVER_PORT="587"
EMAIL_FROM_ADDRESS=""
EMAIL_ERRORS_TO=""
EMAIL_SSL="FALSE"
EMAIL_TLS="FALSE"
if [ -n "$EMAIL_SERVER_URL" ]; then
EMAIL_ACCESS_KEY=$(prompt_value "SMTP username" "")
EMAIL_SECRET_KEY=$(prompt_value "SMTP password" "")
EMAIL_SERVER_PORT=$(prompt_value "SMTP port" "587")
EMAIL_FROM_ADDRESS=$(prompt_value "From email address" "no-reply@orcpub.com")
EMAIL_ERRORS_TO=$(prompt_value "Error notification email" "")
EMAIL_SSL=$(prompt_value "Use SSL? (TRUE/FALSE)" "FALSE")
EMAIL_TLS=$(prompt_value "Use TLS? (TRUE/FALSE)" "FALSE")
fi
header "Initial Admin User"
INIT_ADMIN_USER="${INIT_ADMIN_USER:-}"
INIT_ADMIN_EMAIL="${INIT_ADMIN_EMAIL:-}"
INIT_ADMIN_PASSWORD="${INIT_ADMIN_PASSWORD:-}"
if [ -n "$INIT_ADMIN_USER" ] && [ -n "$INIT_ADMIN_EMAIL" ] && [ -n "$INIT_ADMIN_PASSWORD" ]; then
info "Using admin user from environment: ${INIT_ADMIN_USER} <${INIT_ADMIN_EMAIL}>"
elif [ "${AUTO_MODE}" = "true" ]; then
INIT_ADMIN_USER="admin"
INIT_ADMIN_EMAIL="admin@localhost"
INIT_ADMIN_PASSWORD=$(generate_password 16)
change "Generated admin user: ${INIT_ADMIN_USER} <${INIT_ADMIN_EMAIL}>"
change "Generated admin password: ${INIT_ADMIN_PASSWORD}"
info "Change these in .env before going to production."
else
info "Optionally create an initial admin account."
info "You can skip this and create users later with ./docker-user.sh"
echo ""
INIT_ADMIN_USER=$(prompt_value "Admin username (leave empty to skip)" "")
if [ -n "$INIT_ADMIN_USER" ]; then
_default_email="${INIT_ADMIN_USER}@example.com"
_default_pw="$(generate_password 16)"
INIT_ADMIN_EMAIL=$(prompt_value "Admin email" "$_default_email")
INIT_ADMIN_PASSWORD=$(prompt_value "Admin password" "$_default_pw")
if [ -z "$INIT_ADMIN_EMAIL" ] || [ -z "$INIT_ADMIN_PASSWORD" ]; then
warn "Email and password are required. Skipping admin user setup."
INIT_ADMIN_USER=""
INIT_ADMIN_EMAIL=""
INIT_ADMIN_PASSWORD=""
fi
fi
fi
info "Writing .env file..."
write_env_file
setup_directories
setup_ssl_certs
echo ""
}
usage() {
cat <<USAGE
Usage: ./${SCRIPT_NAME} [OPTIONS]
No flags (default):
./${SCRIPT_NAME} Full pipeline: setup -> build -> up (interactive)
./${SCRIPT_NAME} --auto Same, non-interactive (CI/scripting)
Individual steps:
--check Validate .env and environment (read-only)
--build Build Docker images only
--up Deploy as a Docker Swarm stack
--down Teardown (auto-detects Swarm vs Compose)
Setup & secrets:
--secrets Convert .env passwords to Docker secret files
--swarm Convert .env passwords to Docker Swarm secrets
--upgrade Update an existing .env to the latest format
--upgrade-secrets Upgrade .env + create Docker secret files (one step)
--upgrade-swarm Upgrade .env + create Swarm secrets (one step)
Modifiers:
--auto Non-interactive mode; accept all defaults
--force Overwrite existing .env file
--help Show this help message
Swarm (flags compose together):
./${SCRIPT_NAME} --swarm --auto --build --up # Zero to running stack
Examples:
./${SCRIPT_NAME} # Full pipeline — interactive
./${SCRIPT_NAME} --auto # Full pipeline — accept defaults (CI)
./${SCRIPT_NAME} --down # Stop everything
./${SCRIPT_NAME} --check # Validate without changes
./${SCRIPT_NAME} --build # Build images only
./${SCRIPT_NAME} --upgrade # Fix old .env format
./${SCRIPT_NAME} --swarm --auto # Generate .env + init Swarm + create secrets
./${SCRIPT_NAME} --build --up # Build + deploy (Swarm only)
USAGE
}
# ---------------------------------------------------------------------------
# Parse arguments
# ---------------------------------------------------------------------------
AUTO_MODE=false
BUILD_MODE=false
CHECK_MODE=false
DOWN_MODE=false
UP_MODE=false
FORCE_MODE=false
SECRETS_MODE=false
SWARM_MODE=false
UPGRADE_MODE=false
for arg in "$@"; do
case "$arg" in
--auto) AUTO_MODE=true ;;
--check) CHECK_MODE=true ;;
--build) BUILD_MODE=true ;;
--down) DOWN_MODE=true ;;
--up) UP_MODE=true ;;
--force) FORCE_MODE=true ;;
--secrets) SECRETS_MODE=true ;;
--swarm) SWARM_MODE=true ;;
--upgrade) UPGRADE_MODE=true ;;
--upgrade-swarm) UPGRADE_MODE=true; SWARM_MODE=true ;;
--upgrade-secrets) UPGRADE_MODE=true; SECRETS_MODE=true ;;
--help) usage; exit 0 ;;
*)
error "Unknown option: $arg"
usage
exit 1
;;
esac
done
# Conflict: --secrets and --swarm are mutually exclusive
if [ "$SECRETS_MODE" = "true" ] && [ "$SWARM_MODE" = "true" ] && [ "$UPGRADE_MODE" != "true" ]; then
error "--secrets and --swarm are mutually exclusive."
echo " --secrets writes secrets as local files (Compose)"
echo " --swarm stores secrets in the Swarm Raft log (Swarm)"
echo ""
echo "Pick one based on your deployment:"
echo " Compose → ./${SCRIPT_NAME} --secrets"
echo " Swarm → ./${SCRIPT_NAME} --swarm"
exit 1
fi
# Conflict: --down is standalone
if [ "$DOWN_MODE" = "true" ]; then
for _m in "$UP_MODE" "$BUILD_MODE" "$SECRETS_MODE" "$SWARM_MODE" "$UPGRADE_MODE"; do
if [ "$_m" = "true" ]; then
error "--down cannot be combined with other mode flags."
exit 1
fi
done
fi
# Detect naked mode (no mode flags set)
_any_mode=false
for _m in "$CHECK_MODE" "$SECRETS_MODE" "$SWARM_MODE" "$BUILD_MODE" "$UP_MODE" "$UPGRADE_MODE" "$DOWN_MODE"; do
[ "$_m" = "true" ] && _any_mode=true
done
# ---------------------------------------------------------------------------
# Check mode (--check) — read-only validation
# ---------------------------------------------------------------------------
# Validates .env has all required variables, checks for common issues,
# and reports shell env conflicts. Makes no changes.
if [ "$CHECK_MODE" = "true" ]; then
header "Dungeon Master's Vault — Environment Check"
if [ ! -f "$ENV_FILE" ]; then
warn "No .env file found."
echo " 1) Interactive setup (prompts for each value)"
echo " 2) Auto setup (generates random passwords, safe defaults)"
echo " 3) Skip"
read -rp "Choice [1]: " _create || true
case "${_create:-1}" in
1) exec "$0" ;;
2) exec "$0" --auto ;;
*) exit 0 ;;
esac
fi
ERRORS=0
WARNING_MSGS=()
ENV_CONFLICTS=()
# Required variables — check .env first, then secrets/ files
_has_secrets_dir=false
[ -d "${SCRIPT_DIR}/secrets" ] && _has_secrets_dir=true
for _var in DATOMIC_URL DATOMIC_PASSWORD ADMIN_PASSWORD SIGNATURE; do
_val=$(read_env_val "$_var" "$ENV_FILE")
if [ -n "$_val" ]; then
info " ${_var}: OK"
elif [ "$_has_secrets_dir" = "true" ]; then
# Map var names to secret file names
case "$_var" in
DATOMIC_PASSWORD) _secret_file="datomic_password" ;;
ADMIN_PASSWORD) _secret_file="admin_password" ;;
SIGNATURE) _secret_file="signature" ;;
*) _secret_file="" ;;
esac
if [ -n "$_secret_file" ] && [ -f "${SCRIPT_DIR}/secrets/${_secret_file}" ]; then
info " ${_var}: OK (via secrets/${_secret_file})"
elif [ -n "$_secret_file" ] && docker secret inspect "$_secret_file" &>/dev/null; then
info " ${_var}: OK (via Swarm secret ${_secret_file})"
else
warn " ${_var}: MISSING"
WARNING_MSGS+=("${_var} is missing from .env")
ERRORS=$((ERRORS + 1))
fi
else
warn " ${_var}: MISSING"
WARNING_MSGS+=("${_var} is missing from .env")
ERRORS=$((ERRORS + 1))
fi
done
echo ""
# URL health checks
_url=$(read_env_val DATOMIC_URL "$ENV_FILE")
if [[ "$_url" == *"password="* ]]; then
warn " DATOMIC_URL has embedded password (legacy format)"
warn " Run ./${SCRIPT_NAME} --upgrade to clean it"
WARNING_MSGS+=("DATOMIC_URL has embedded password")
ERRORS=$((ERRORS + 1))
fi
if [[ "$_url" == *"datomic:free://"* ]]; then
warn " DATOMIC_URL uses old Free protocol"
warn " Run ./${SCRIPT_NAME} --upgrade to convert to datomic:dev://"
WARNING_MSGS+=("DATOMIC_URL uses Free protocol")
ERRORS=$((ERRORS + 1))
fi
if [[ "$_url" == *"localhost"* ]]; then
warn " DATOMIC_URL contains 'localhost' (should be 'datomic' for Docker)"
warn " Run ./${SCRIPT_NAME} --upgrade to fix"
WARNING_MSGS+=("DATOMIC_URL contains localhost")
ERRORS=$((ERRORS + 1))
fi
echo ""
# Shell env conflicts
for _var in DATOMIC_URL DATOMIC_PASSWORD SIGNATURE ADMIN_PASSWORD; do
check_env_conflict "$_var"
done
# Required files and directories
echo ""
check_file ".env" "$ENV_FILE"
check_file "docker-compose.yaml" "${SCRIPT_DIR}/docker-compose.yaml"
check_file "nginx.conf.template" "${SCRIPT_DIR}/deploy/nginx.conf.template"
check_dir "data/" "${SCRIPT_DIR}/data"
check_dir "logs/" "${SCRIPT_DIR}/logs"
echo ""
if [ "$ERRORS" -eq 0 ]; then
success "All checks passed"
else
warn "${ERRORS} issue(s) found."
read -rp "Run upgrade to fix? [Y/n]: " _fix || true
if [[ "${_fix,,}" =~ ^(y|)$ ]]; then
exec "$0" --upgrade
fi
fi
exit 0
fi
# ---------------------------------------------------------------------------
# Down mode (--down) — teardown running services
# ---------------------------------------------------------------------------
if [ "$DOWN_MODE" = "true" ]; then
header "Dungeon Master's Vault — Teardown"
_swarm_state=$(docker info --format '{{.Swarm.LocalNodeState}}' 2>/dev/null || true)
if [ "$_swarm_state" = "active" ] && docker stack ls 2>/dev/null | grep -q orcpub; then
info "Swarm stack detected."
if confirm_action "Remove Swarm stack 'orcpub'?"; then
docker stack rm orcpub 2>&1
change "Swarm stack removed."
fi
elif docker compose ps -q 2>/dev/null | head -1 | grep -q .; then
info "Compose services detected."
if confirm_action "Tear down Compose services?"; then
docker compose down 2>&1
change "Compose services stopped."
fi
else
info "No running services found."
fi
exit 0
fi
# ---------------------------------------------------------------------------
# Secrets migration (--secrets mode)
# ---------------------------------------------------------------------------
# Reads passwords from .env or shell environment and writes them as
# individual secret files. Works whether you use .env or export vars directly.
# Auto-generates docker-compose.secrets.yaml and wires it via COMPOSE_FILE.
if [ "$SECRETS_MODE" = "true" ] && [ "$UPGRADE_MODE" != "true" ]; then
header "Dungeon Master's Vault — Secrets Migration"
# Ask if they're running Swarm — different flow entirely
if [ "${AUTO_MODE}" != "true" ]; then
echo "This will create secret files on your machine (works with docker compose)."
echo "If you're running Docker Swarm, secrets are stored in the cluster instead."
echo ""
read -rp "Are you using Docker Swarm? [y/N]: " _is_swarm || true
if [[ "${_is_swarm,,}" == "y" ]]; then
exec "$0" --swarm
fi
fi
SECRETS_DIR="${SCRIPT_DIR}/secrets"
# If no .env exists, generate one (enables one-step secrets setup)
if [ ! -f "$ENV_FILE" ]; then
generate_env
fi
read_passwords "--secrets"
# Check for existing secrets (--auto implies --force here)
if [ -d "$SECRETS_DIR" ] && [ "$FORCE_MODE" = "false" ] && [ "$AUTO_MODE" != "true" ]; then
warn "secrets/ directory already exists. Use --force to overwrite."
exit 1
fi
mkdir -p "$SECRETS_DIR"
# Write each password to its own file (printf, not echo, to avoid trailing newline)
printf '%s' "$_pw_datomic" > "${SECRETS_DIR}/datomic_password" || { error "Failed to write ${SECRETS_DIR}/datomic_password"; exit 1; }
printf '%s' "$_pw_admin" > "${SECRETS_DIR}/admin_password" || { error "Failed to write ${SECRETS_DIR}/admin_password"; exit 1; }
printf '%s' "$_pw_signature" > "${SECRETS_DIR}/signature" || { error "Failed to write ${SECRETS_DIR}/signature"; exit 1; }
chmod 600 "${SECRETS_DIR}"/*
change "Created secrets/datomic_password"
change "Created secrets/admin_password"
change "Created secrets/signature"
change "File permissions set to 600"
unset _pw_datomic _pw_admin _pw_signature
# Generate compose override so secrets are wired in automatically
write_compose_secrets "file"
# Revert transactor host to compose-compatible binding if previously
# switched to Swarm mode (host=0.0.0.0).
switch_transactor_host "compose"
# Move secret vars from .env to a backup file so they aren't duplicated
BACKUP_FILE="${ENV_FILE}.secrets.backup"
SECRET_VARS="DATOMIC_PASSWORD|ADMIN_PASSWORD|SIGNATURE"
_moved=0
if grep -qE "^(${SECRET_VARS})=" "$ENV_FILE" 2>/dev/null; then
grep -E "^(${SECRET_VARS})=" "$ENV_FILE" >> "$BACKUP_FILE"
sed -i -E "/^(${SECRET_VARS})=/d" "$ENV_FILE"
_moved=1
fi
echo ""
success "Done! Passwords are in secrets/, compose is configured."
if [ "$_moved" -eq 1 ]; then
change "Moved DATOMIC_PASSWORD, ADMIN_PASSWORD, SIGNATURE from .env to .env.secrets.backup"
warn "Delete .env.secrets.backup after verifying secrets work."
fi
echo ""
next "docker compose down && docker compose up -d"
exit 0
fi
# ---------------------------------------------------------------------------
# Swarm secrets (--swarm mode)
# ---------------------------------------------------------------------------
# Creates Docker secrets via `docker secret create` for use in Swarm clusters.
# Secrets are stored encrypted in the Swarm Raft log and delivered to
# containers in memory — never written to disk on any node.
if [ "$SWARM_MODE" = "true" ] && [ "$UPGRADE_MODE" != "true" ]; then
header "Dungeon Master's Vault — Swarm Secrets"
# Check for running Compose containers — they'll conflict with Swarm networking
_running=$(docker compose ps -q 2>/dev/null | head -1 || true)
if [ -n "$_running" ]; then
warn "Compose containers are running. These must be stopped before Swarm deploy."
if confirm_action "Stop Compose services now?"; then
docker compose down 2>&1 || true
change "Compose services stopped."
else
warn "Swarm deploy will fail if Compose networks overlap. Continuing anyway..."
fi
fi
# Verify this node is part of a Swarm — offer to initialize if not
_swarm_state=$(docker info --format '{{.Swarm.LocalNodeState}}' 2>/dev/null || true)
if [ "$_swarm_state" != "active" ]; then
warn "This Docker node is not in Swarm mode."
echo ""
if confirm_action "Initialize a single-node Swarm now?"; then
docker swarm init 2>&1 || { error "Failed to initialize Swarm."; exit 1; }
change "Docker Swarm initialized."
else
info "Run 'docker swarm init' manually, then re-run: ./${SCRIPT_NAME} --swarm"
exit 0
fi
fi
# If no .env exists, generate one (enables one-step swarm setup)
if [ ! -f "$ENV_FILE" ]; then
generate_env
fi
read_passwords "--swarm"
# Check for existing secrets and handle accordingly
_existing=0
_created=0
for _name in datomic_password admin_password signature; do
if docker secret inspect "$_name" &>/dev/null; then
if [ "$FORCE_MODE" = "true" ]; then
# Swarm doesn't support updating secrets — must remove and recreate.
# Services using the secret must be stopped first.
docker secret rm "$_name" &>/dev/null || true
warn "Removed existing secret: $_name (--force)"
else
warn "Secret already exists: $_name (use --force to replace)"
_existing=$((_existing + 1))
continue
fi
fi
# Get the right password value for this secret name
case "$_name" in
datomic_password) _val="$_pw_datomic" ;;
admin_password) _val="$_pw_admin" ;;
signature) _val="$_pw_signature" ;;
esac
if printf '%s' "$_val" | docker secret create "$_name" - 2>/dev/null; then
change "Created Swarm secret: $_name"
_created=$((_created + 1))
else
error "Failed to create Swarm secret: $_name"
exit 1
fi
done
unset _pw_datomic _pw_admin _pw_signature _val
echo ""
if [ "$_existing" -gt 0 ] && [ "$FORCE_MODE" = "false" ]; then
warn "${_existing} secret(s) already existed (skipped)."
fi
if [ "$_created" -gt 0 ]; then
change "${_created} Swarm secret(s) created."
fi
# Generate compose override so secrets are wired in automatically
write_compose_secrets "external"
# Switch transactor to Swarm-compatible host binding.
switch_transactor_host "swarm"
set_env_val ALT_HOST datomic "$ENV_FILE"
change "ALT_HOST=datomic (peer fallback via Docker DNS)"
echo ""
success "Done! Swarm secrets created, compose is configured."
# If --build or --up also specified, fall through to those blocks.
if [ "$BUILD_MODE" != "true" ] && [ "$UP_MODE" != "true" ]; then
echo ""
echo "Next steps:"
echo ""
printf ' %sBUILD%s images:\n' "$color_cyan" "$color_reset"
next " ./${SCRIPT_NAME} --build"
echo ""
printf ' %sDEPLOY%s as a Swarm stack:\n' "$color_cyan" "$color_reset"
next " ./${SCRIPT_NAME} --up"
echo ""
info "Or both in one step: ./${SCRIPT_NAME} --build --up"
echo ""
echo "--- Tip: Managing secrets later ---"
echo " docker secret ls # List all secrets"
echo " docker secret inspect <name> # Show metadata (not the value)"
echo " docker secret rm <name> # Remove (stop services first)"
exit 0
fi
fi
# ---------------------------------------------------------------------------
# Build mode (--build) — build Docker images
# ---------------------------------------------------------------------------
if [ "$BUILD_MODE" = "true" ] && [ "$UP_MODE" != "true" ]; then
header "Dungeon Master's Vault — Build"
if ! docker compose version &>/dev/null; then
error "docker compose is not available."
exit 1
fi
if [ ! -f "$ENV_FILE" ]; then
error "No .env file found."
echo " Run setup first: ./${SCRIPT_NAME} [--auto]"
if confirm_action "Run setup now?"; then
generate_env
else
exit 1
fi
fi
info "Building images..."
docker compose build || { error "Build failed."; exit 1; }
echo ""
success "Images built!"
exit 0
fi
# ---------------------------------------------------------------------------
# Up mode (--up) — deploy as a Docker Swarm stack
# ---------------------------------------------------------------------------
if [ "$UP_MODE" = "true" ]; then
header "Dungeon Master's Vault — Swarm Deploy"
if ! docker compose version &>/dev/null; then
error "docker compose is not available."
exit 1
fi
# Verify Swarm is active
_swarm_state=$(docker info --format '{{.Swarm.LocalNodeState}}' 2>/dev/null || true)