-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathsetup.sh
More file actions
executable file
·3001 lines (2655 loc) · 120 KB
/
Copy pathsetup.sh
File metadata and controls
executable file
·3001 lines (2655 loc) · 120 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
# ============================================================================
# Vandalizer — Interactive Setup Wizard
# AI-powered document intelligence for research administration
#
# Run from the project root:
# ./setup.sh First-time setup (or re-run shows the main menu)
# ./setup.sh --repair Diagnose and fix a broken deployment
# ./setup.sh --upgrade Scan origin for new code & catalog, apply what's outdated
# ./setup.sh --redeploy Rebuild and restart from current code (no git pull)
# ./setup.sh --seed Update verified catalog (add/refresh, retire dropped items with your OK)
# ./setup.sh --reset-catalog Wipe catalog metadata and re-seed from current version
# ./setup.sh --reingest Re-ingest all knowledge base content into ChromaDB
# ./setup.sh --reset-email Reconfigure email provider (SMTP or Resend)
# ./setup.sh --cron-setup Schedule automated upgrades via crontab
# ./setup.sh --cron-remove Remove the scheduled auto-update entry
# ./setup.sh --auto-update Non-interactive upgrade for cron (logs to .auto_update.log)
#
# Re-running with no flags on an existing deployment opens a 4-section menu:
# Monitor — system status, log tailing, version check, full diagnostics
# Deploy — repair, redeploy, upgrade, full setup, email reconfigure
# Catalog — update / reset / re-ingest knowledge bases
# Auto update — schedule, remove, run-now, view log
# ============================================================================
set -uo pipefail
# ---------------------------------------------------------------------------
# Colors & styles
# ---------------------------------------------------------------------------
BOLD='\033[1m'
DIM='\033[2m'
ITALIC='\033[3m'
RESET='\033[0m'
GREEN='\033[38;5;114m'
RED='\033[38;5;203m'
YELLOW='\033[38;5;221m'
BLUE='\033[38;5;111m'
CYAN='\033[38;5;117m'
MAGENTA='\033[38;5;183m'
GRAY='\033[38;5;245m'
WHITE='\033[38;5;255m'
DEEP_CYAN='\033[38;5;44m'
VIOLET='\033[38;5;141m'
BRIGHT_GREEN='\033[38;5;82m'
ORANGE='\033[38;5;208m'
# Nerd symbols
SYM_CHECK="${GREEN}✓${RESET}"
SYM_CROSS="${RED}✗${RESET}"
SYM_WARN="${YELLOW}⚠${RESET}"
SYM_ARROW="${CYAN}▸${RESET}"
SYM_DOT="${MAGENTA}●${RESET}"
SYM_NEURAL="${VIOLET}◆${RESET}"
SYM_PULSE="${DEEP_CYAN}⟐${RESET}"
# ---------------------------------------------------------------------------
# State
# ---------------------------------------------------------------------------
ENV_FILE="backend/.env"
ENV_EXAMPLE="backend/.env.example"
COMPOSE_CMD="docker compose"
CONTAINER_CLI="docker"
SETUP_LOG=".setup.log"
ERRORS=()
# Version state — populated by show_versions(), reused by scan_and_upgrade().
CODE_VERSION_LOCAL=""
CODE_VERSION_LATEST=""
CATALOG_VERSION_LOCAL=""
CATALOG_VERSION_LATEST=""
SEEDS_VERSION_FILE="backend/seeds/VERSION"
CODE_VERSION_FILE=".vandalizer_version" # written by upgrade.sh (image deploys)
CATALOG_VERSION_HOST_FILE=".vandalizer_catalog_version" # written after a successful seed
# Use only compose.yaml — skip compose.override.yaml (dev port overrides).
# This keeps infrastructure ports off the host so Vandalizer can co-exist
# with other services (Mongo, Redis, etc.) on the same server.
export COMPOSE_FILE=compose.yaml
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
log() { echo "$@" >> "$SETUP_LOG"; }
die() {
echo ""
echo -e " ${RED}${BOLD}Fatal:${RESET} $1"
echo ""
exit 1
}
# ---------------------------------------------------------------------------
# Container-engine compatibility layer
#
# The compose frontend may be Docker Compose v2, docker-compose v1, or
# podman-compose. Their `ps --format` templates differ (podman-compose
# forwards to `podman ps`, which has no .Service/.Health fields), so all
# container introspection goes through the engine CLI instead, keyed on the
# com.docker.compose.* labels that every compose implementation attaches.
# ---------------------------------------------------------------------------
# Compose project name: explicit override, else the lowercased directory
# name — the default every compose implementation derives.
compose_project() {
if [[ -n "${COMPOSE_PROJECT_NAME:-}" ]]; then
echo "$COMPOSE_PROJECT_NAME"
else
basename "$PWD" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9_-]//g'
fi
}
# Name of the container backing a compose service; empty if none exists.
compose_container() {
local c
# Prefer a running container: `ps -a` lists exited and one-off `compose run`
# containers too, newest first, and an exec against one of those fails with
# a confusing error instead of "the API container is not running".
for flag in "" "-a"; do
c=$($CONTAINER_CLI ps $flag \
--filter "label=com.docker.compose.project=$(compose_project)" \
--filter "label=com.docker.compose.service=$1" \
--format '{{.Names}}' 2>/dev/null | head -1)
[[ -n "$c" ]] && break
done
echo "$c"
}
# State (running/exited/restarting/...) of a service's container; empty if
# the container doesn't exist.
compose_state() {
local c
c=$(compose_container "$1")
[[ -n "$c" ]] || return 0
$CONTAINER_CLI inspect --format '{{.State.Status}}' "$c" 2>/dev/null
}
# Health (healthy/unhealthy/starting) of a service's container; empty when
# the container doesn't exist or defines no healthcheck.
compose_health() {
local c
c=$(compose_container "$1")
[[ -n "$c" ]] || return 0
$CONTAINER_CLI inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{end}}' "$c" 2>/dev/null
}
# Typewriter effect — prints text one character at a time
typewriter() {
local text="$1"
local delay="${2:-0.02}"
for (( i=0; i<${#text}; i++ )); do
printf '%s' "${text:$i:1}"
sleep "$delay"
done
}
# Animated spinner while a background process runs
spin() {
local pid=$1
local label="${2:-Processing}"
local frames=("⠋" "⠙" "⠹" "⠸" "⠼" "⠴" "⠦" "⠧" "⠇" "⠏")
local i=0
while kill -0 "$pid" 2>/dev/null; do
printf "\r ${CYAN}${frames[$i]}${RESET} ${DIM}%s${RESET} " "$label"
i=$(( (i + 1) % ${#frames[@]} ))
sleep 0.08
done
wait "$pid"
return $?
}
# Run a command with a spinner, show pass/fail
run_step() {
local label="$1"
shift
"$@" >> "$SETUP_LOG" 2>&1 &
local pid=$!
spin "$pid" "$label"
if wait "$pid"; then
printf "\r ${SYM_CHECK} %s\n" "$label"
return 0
else
printf "\r ${SYM_CROSS} %s\n" "$label"
ERRORS+=("$label")
return 1
fi
}
# Prompt for input with a default value
prompt() {
local label="$1"
local default="$2"
local var_name="$3"
local is_secret="${4:-false}"
if [[ -n "$default" ]]; then
echo -ne " ${SYM_ARROW} ${label} ${DIM}[${default}]${RESET}: "
else
echo -ne " ${SYM_ARROW} ${label}: "
fi
local value
if [[ "$is_secret" == "true" ]]; then
read -rs value
echo ""
else
read -r value
fi
value="${value:-$default}"
printf -v "$var_name" '%s' "$value"
}
# Prompt yes/no
confirm() {
local label="$1"
local default="${2:-y}"
local hint
if [[ "$default" == "y" ]]; then hint="Y/n"; else hint="y/N"; fi
echo -ne " ${SYM_ARROW} ${label} ${DIM}[${hint}]${RESET}: "
local answer
read -r answer
answer="${answer:-$default}"
[[ "$answer" =~ ^[Yy] ]]
}
# Section header with neural-net decoration
section() {
local num="$1"
local title="$2"
echo ""
echo -e " ${VIOLET}┌─${RESET} ${BOLD}${WHITE}PHASE ${num}${RESET} ${DIM}─────────────────────────────────────${RESET}"
echo -e " ${VIOLET}│${RESET} ${BOLD}${CYAN}${title}${RESET}"
echo -e " ${VIOLET}└──────────────────────────────────────────────${RESET}"
echo ""
}
# ---------------------------------------------------------------------------
# Banner
# ---------------------------------------------------------------------------
show_banner() {
clear 2>/dev/null || true
echo ""
echo -e "${MAGENTA}"
cat << 'BANNER'
██╗ ██╗ █████╗ ███╗ ██╗██████╗ █████╗ ██╗ ██╗███████╗███████╗██████╗
██║ ██║██╔══██╗████╗ ██║██╔══██╗██╔══██╗██║ ██║╚══███╔╝██╔════╝██╔══██╗
██║ ██║███████║██╔██╗ ██║██║ ██║███████║██║ ██║ ███╔╝ █████╗ ██████╔╝
╚██╗ ██╔╝██╔══██║██║╚██╗██║██║ ██║██╔══██║██║ ██║ ███╔╝ ██╔══╝ ██╔══██╗
╚████╔╝ ██║ ██║██║ ╚████║██████╔╝██║ ██║███████╗██║███████╗███████╗██║ ██║
╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝╚══════╝╚══════╝╚═╝ ╚═╝
BANNER
echo -e "${RESET}"
echo -e " ${DIM}──────────────────────────────────────────────────────────────────────────────${RESET}"
echo -e " ${BOLD}${WHITE} AI-Powered Document Intelligence${RESET} ${DIM}│${RESET} ${CYAN}Interactive Setup Wizard${RESET}"
echo -e " ${DIM}──────────────────────────────────────────────────────────────────────────────${RESET}"
echo ""
echo -ne " "
typewriter "Initializing deployment sequence..." 0.03
echo ""
sleep 0.5
show_versions
}
# ---------------------------------------------------------------------------
# Version detection — code (release tag) and information set (seed catalog)
# ---------------------------------------------------------------------------
# Strip a leading 'v' so sort -V can compare across mixed schemes.
_norm_ver() { echo "${1#v}"; }
# is_newer A B → 0 if A is strictly newer than B, 1 otherwise.
# Treats "" or "unknown" as oldest. Uses sort -V (handles semver and CalVer).
is_newer() {
local a="${1:-}" b="${2:-}"
[[ -z "$a" || "$a" == "unknown" ]] && return 1
[[ -z "$b" || "$b" == "unknown" ]] && return 0
[[ "$a" == "$b" ]] && return 1
local na nb top
na=$(_norm_ver "$a"); nb=$(_norm_ver "$b")
top=$(printf '%s\n%s\n' "$na" "$nb" | sort -V | tail -1)
[[ "$top" == "$na" ]]
}
# Code version installed locally.
# Prefers .vandalizer_version (written by upgrade.sh on image deploys),
# falls back to the most recent reachable git tag, then to a short SHA.
code_version_local() {
if [[ -f "$CODE_VERSION_FILE" ]]; then
tr -d '[:space:]' < "$CODE_VERSION_FILE"
return
fi
local tag sha
tag=$(git describe --tags --abbrev=0 2>/dev/null || true)
if [[ -n "$tag" ]]; then echo "$tag"; return; fi
sha=$(git rev-parse --short HEAD 2>/dev/null || true)
echo "${sha:-unknown}"
}
# Latest code version published as a git tag on origin.
# Empty on network failure — caller decides how to render.
code_version_latest() {
local tags
tags=$(git ls-remote --tags --refs origin 'v*' 2>/dev/null \
| awk '{print $2}' | sed 's|^refs/tags/||' | sort -V | tail -1 || true)
echo "$tags"
}
# Query the running deployment for the applied catalog version. Returns 0
# and prints the version on success; returns 1 (no output) if Mongo is not
# reachable or no catalog_version is recorded.
_catalog_version_from_db() {
local container
container=$(compose_container mongo)
[[ -z "$container" ]] && return 1
local db="vandalizer"
if [[ -f "$ENV_FILE" ]]; then
local env_db
env_db=$(grep -E "^MONGO_DB=" "$ENV_FILE" 2>/dev/null | head -1 | cut -d'=' -f2-)
[[ -n "$env_db" ]] && db="$env_db"
fi
local v
v=$($CONTAINER_CLI exec "$container" mongosh --quiet --eval \
"var c = db.getSiblingDB('${db}').system_config.findOne({}, {catalog_version: 1}); print(c && c.catalog_version ? c.catalog_version : '');" \
2>/dev/null | tr -d '[:space:]')
[[ -n "$v" ]] || return 1
echo "$v"
}
# Catalog version installed locally. Source of truth is SystemConfig in Mongo
# (written by scripts/seed_catalog.py on every successful seed); the host-side
# file is just a cache so non-Mongo paths (cron pre-flight, etc.) still work.
catalog_version_local() {
local from_db
if from_db=$(_catalog_version_from_db) && [[ -n "$from_db" ]]; then
echo "$from_db" > "$CATALOG_VERSION_HOST_FILE" 2>/dev/null || true
echo "$from_db"
return
fi
[[ -f "$CATALOG_VERSION_HOST_FILE" ]] || { echo "unknown"; return; }
tr -d '[:space:]' < "$CATALOG_VERSION_HOST_FILE"
}
# Latest catalog version on origin's default branch.
# Uses a cached git fetch; empty on network failure.
catalog_version_latest() {
if [[ -d .git ]]; then
git fetch --quiet origin 2>/dev/null || true
# Try common default-branch refs in order.
for ref in origin/HEAD origin/main origin/master; do
local v
v=$(git show "$ref:$SEEDS_VERSION_FILE" 2>/dev/null | head -1 | tr -d '[:space:]' || true)
if [[ -n "$v" ]]; then echo "$v"; return; fi
done
fi
echo ""
}
# Render one version row with a status marker.
_render_version_row() {
local label="$1" current="$2" latest="$3"
local status
if [[ -z "$latest" ]]; then
status="${DIM}? could not check remote${RESET}"
elif is_newer "$latest" "$current"; then
status="${ORANGE}⟐ update available — ${latest}${RESET}"
else
status="${GREEN}✓ up to date${RESET}"
fi
printf " ${SYM_NEURAL} ${BOLD}%-8s${RESET} ${CYAN}%-14s${RESET} %b\n" \
"$label" "$current" "$status"
}
# Print code + catalog versions. Caches results in module-level vars so
# scan_and_upgrade() can reuse them without re-fetching.
show_versions() {
CODE_VERSION_LOCAL=$(code_version_local)
CODE_VERSION_LATEST=$(code_version_latest)
CATALOG_VERSION_LOCAL=$(catalog_version_local)
CATALOG_VERSION_LATEST=$(catalog_version_latest)
echo ""
_render_version_row "Code" "$CODE_VERSION_LOCAL" "$CODE_VERSION_LATEST"
_render_version_row "Catalog" "$CATALOG_VERSION_LOCAL" "$CATALOG_VERSION_LATEST"
echo ""
}
# ---------------------------------------------------------------------------
# Phase 0: Pre-flight checks
# ---------------------------------------------------------------------------
preflight() {
section "0" "Pre-Flight Diagnostics"
# Container engine (Docker, or Podman — possibly behind the docker wrapper)
if command -v docker &>/dev/null; then
local docker_version
docker_version=$(docker --version 2>/dev/null | head -1)
echo -e " ${SYM_CHECK} Docker detected ${DIM}(${docker_version})${RESET}"
elif command -v podman &>/dev/null; then
CONTAINER_CLI="podman"
local podman_version
podman_version=$(podman --version 2>/dev/null | head -1)
echo -e " ${SYM_CHECK} Podman detected ${DIM}(${podman_version})${RESET}"
else
die "No container engine found. Install Docker (https://docs.docker.com/get-docker/) or Podman (https://podman.io/docs/installation)."
fi
# Compose frontend: docker compose v2, docker-compose v1, or podman-compose
if ! $COMPOSE_CMD version &>/dev/null 2>&1; then
COMPOSE_CMD="docker-compose"
if ! $COMPOSE_CMD version &>/dev/null 2>&1; then
COMPOSE_CMD="podman-compose"
if ! $COMPOSE_CMD version &>/dev/null 2>&1; then
die "No Compose implementation found. Install Docker Compose (https://docs.docker.com/compose/install/) or podman-compose."
fi
fi
fi
local compose_version
compose_version=$($COMPOSE_CMD version --short 2>/dev/null || $COMPOSE_CMD version 2>/dev/null | head -1)
echo -e " ${SYM_CHECK} Compose detected ${DIM}(${COMPOSE_CMD}, ${compose_version})${RESET}"
# Engine is usable (daemon running, or rootless podman configured)
if $CONTAINER_CLI info &>/dev/null 2>&1; then
echo -e " ${SYM_CHECK} Container engine is running"
else
die "Container engine is not responding. Start Docker Desktop / the Docker service, or check 'podman info'."
fi
# compose.yaml
if [[ -f "compose.yaml" ]] || [[ -f "docker-compose.yml" ]] || [[ -f "docker-compose.yaml" ]]; then
echo -e " ${SYM_CHECK} Compose file found"
else
die "No compose.yaml found. Run this script from the vandalizer project root."
fi
# .env.example
if [[ -f "$ENV_EXAMPLE" ]]; then
echo -e " ${SYM_CHECK} Environment template found"
else
die "Missing ${ENV_EXAMPLE}. Are you in the vandalizer project root?"
fi
echo ""
echo -e " ${BRIGHT_GREEN}${BOLD}Systems nominal.${RESET} ${DIM}All pre-flight checks passed.${RESET}"
}
# ---------------------------------------------------------------------------
# Set or add a key=value in the backend .env file
# ---------------------------------------------------------------------------
set_env() {
local key="$1" value="$2"
if grep -q "^${key}=" "$ENV_FILE" 2>/dev/null; then
sed -i.bak "s|^${key}=.*|${key}=${value}|" "$ENV_FILE" && rm -f "${ENV_FILE}.bak"
else
echo "${key}=${value}" >> "$ENV_FILE"
fi
}
# ---------------------------------------------------------------------------
# Email configuration (shared by first-time setup and --reset-email)
# ---------------------------------------------------------------------------
configure_email() {
echo ""
echo -e " ${DIM} 1)${RESET} ${CYAN}SMTP${RESET} ${DIM}— traditional mail server${RESET}"
echo -e " ${DIM} 2)${RESET} ${CYAN}Resend${RESET} ${DIM}— API-based email (resend.com)${RESET}"
echo ""
echo -ne " ${SYM_ARROW} Email provider ${DIM}[1]${RESET}: "
local provider_choice
read -r provider_choice
provider_choice="${provider_choice:-1}"
if [[ "$provider_choice" == "2" ]]; then
# --- Resend ---
set_env "EMAIL_PROVIDER" "resend"
echo ""
prompt "Resend API key" "" RESEND_API_KEY true
prompt "From email (must be verified in Resend)" "" RESEND_FROM
prompt "From name" "Vandalizer" RESEND_FROM_NAME
set_env "RESEND_API_KEY" "$RESEND_API_KEY"
set_env "RESEND_FROM_EMAIL" "$RESEND_FROM"
set_env "RESEND_FROM_NAME" "$RESEND_FROM_NAME"
echo -e " ${SYM_CHECK} Resend configured"
else
# --- SMTP ---
set_env "EMAIL_PROVIDER" "smtp"
echo ""
prompt "SMTP host" "" SMTP_HOST
prompt "SMTP port" "587" SMTP_PORT
prompt "SMTP username" "" SMTP_USER
prompt "SMTP password" "" SMTP_PASSWORD true
prompt "From email" "" SMTP_FROM
prompt "From name" "Vandalizer" SMTP_FROM_NAME
set_env "SMTP_HOST" "$SMTP_HOST"
set_env "SMTP_PORT" "$SMTP_PORT"
set_env "SMTP_USER" "$SMTP_USER"
set_env "SMTP_PASSWORD" "$SMTP_PASSWORD"
set_env "SMTP_FROM_EMAIL" "$SMTP_FROM"
set_env "SMTP_FROM_NAME" "$SMTP_FROM_NAME"
echo -e " ${SYM_CHECK} SMTP configured"
fi
}
# ---------------------------------------------------------------------------
# Standalone email reset (./setup.sh --reset-email)
# ---------------------------------------------------------------------------
reset_email() {
section "⚡" "Email Configuration"
if [[ ! -f "$ENV_FILE" ]]; then
die "No backend/.env found. Run ./setup.sh first to create the environment."
fi
configure_email
echo ""
echo -e " ${BRIGHT_GREEN}${BOLD}Email settings updated.${RESET}"
echo -e " ${DIM} Restart the backend for changes to take effect.${RESET}"
}
# ---------------------------------------------------------------------------
# Phase 1: Environment configuration
# ---------------------------------------------------------------------------
configure_env() {
section "1" "Environment Configuration"
# Check for existing .env
if [[ -f "$ENV_FILE" ]]; then
echo -e " ${SYM_WARN} Existing ${BOLD}backend/.env${RESET} detected."
echo ""
if ! confirm "Overwrite and reconfigure?"; then
echo -e " ${DIM} Keeping existing configuration.${RESET}"
# Still check if JWT_SECRET_KEY needs to be set
local existing_jwt
existing_jwt=$(grep -E "^JWT_SECRET_KEY=" "$ENV_FILE" 2>/dev/null | head -1 | cut -d'=' -f2-)
if [[ -z "$existing_jwt" || "$existing_jwt" == "change-me-to-a-random-secret" ]]; then
echo ""
echo -e " ${SYM_WARN} ${YELLOW}JWT_SECRET_KEY is not set or still the default placeholder.${RESET}"
echo -e " ${DIM} Generating a secure key...${RESET}"
local jwt_key
jwt_key=$(python3 -c "import secrets; print(secrets.token_urlsafe(64))" 2>/dev/null || openssl rand -base64 48 2>/dev/null)
sed -i.bak "s|^JWT_SECRET_KEY=.*|JWT_SECRET_KEY=${jwt_key}|" "$ENV_FILE" && rm -f "${ENV_FILE}.bak"
echo -e " ${SYM_CHECK} JWT_SECRET_KEY generated and saved"
fi
check_encryption_key
return
fi
echo ""
fi
# Copy template
cp "$ENV_EXAMPLE" "$ENV_FILE"
echo -e " ${SYM_CHECK} Created ${BOLD}backend/.env${RESET} from template"
# --- Generate JWT secret ---
echo ""
echo -e " ${SYM_NEURAL} ${BOLD}Generating cryptographic secrets...${RESET}"
echo ""
local jwt_key
jwt_key=$(python3 -c "import secrets; print(secrets.token_urlsafe(64))" 2>/dev/null || openssl rand -base64 48 2>/dev/null)
if [[ -z "$jwt_key" ]]; then
die "Could not generate JWT secret. Ensure Python 3 or OpenSSL is available."
fi
sed -i.bak "s|^JWT_SECRET_KEY=.*|JWT_SECRET_KEY=${jwt_key}|" "$ENV_FILE" && rm -f "${ENV_FILE}.bak"
echo -e " ${SYM_CHECK} JWT_SECRET_KEY ${DIM}— authentication token signing key${RESET}"
# --- Generate encryption key ---
local enc_key
enc_key=$(python3 -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())" 2>/dev/null || true)
if [[ -n "$enc_key" ]]; then
sed -i.bak "s|^CONFIG_ENCRYPTION_KEY=.*|CONFIG_ENCRYPTION_KEY=${enc_key}|" "$ENV_FILE" && rm -f "${ENV_FILE}.bak"
echo -e " ${SYM_CHECK} CONFIG_ENCRYPTION_KEY ${DIM}— LLM API key encryption${RESET}"
else
echo -e " ${SYM_WARN} CONFIG_ENCRYPTION_KEY skipped ${DIM}(cryptography package not found locally — bootstrap will auto-generate)${RESET}"
fi
# --- Environment mode ---
echo ""
echo -e " ${SYM_NEURAL} ${BOLD}Deployment profile${RESET}"
echo ""
echo -e " ${DIM} 1)${RESET} ${CYAN}development${RESET} ${DIM}— local dev with hot-reload${RESET}"
echo -e " ${DIM} 2)${RESET} ${CYAN}production${RESET} ${DIM}— optimized for real users${RESET}"
echo ""
echo -ne " ${SYM_ARROW} Select profile ${DIM}[1]${RESET}: "
local env_choice
read -r env_choice
env_choice="${env_choice:-1}"
if [[ "$env_choice" == "2" ]]; then
sed -i.bak "s|^ENVIRONMENT=.*|ENVIRONMENT=production|" "$ENV_FILE" && rm -f "${ENV_FILE}.bak"
echo -e " ${SYM_CHECK} Environment set to ${BOLD}production${RESET}"
echo ""
prompt "Public URL (e.g. https://vandalizer.example.edu)" "http://localhost" FRONTEND_URL
sed -i.bak "s|^FRONTEND_URL=.*|FRONTEND_URL=${FRONTEND_URL}|" "$ENV_FILE" && rm -f "${ENV_FILE}.bak"
echo -e " ${SYM_CHECK} Frontend URL set to ${BOLD}${FRONTEND_URL}${RESET}"
if [[ "$FRONTEND_URL" == http://* ]]; then
echo -e " ${SYM_WARN} ${YELLOW}Production over plain HTTP:${RESET} auth cookies will be set without"
echo -e " ${DIM} the Secure flag so login works. Fine for an isolated/intranet box;${RESET}"
echo -e " ${DIM} use an https:// URL for anything internet-facing.${RESET}"
fi
else
echo -e " ${SYM_CHECK} Environment set to ${BOLD}development${RESET}"
fi
# --- Web server port ---
echo ""
prompt "Web server port" "80" WEB_PORT
# Write WEB_PORT to root .env so docker compose picks it up
local root_env=".env"
if [[ -f "$root_env" ]] && grep -q "^WEB_PORT=" "$root_env" 2>/dev/null; then
sed -i.bak "s|^WEB_PORT=.*|WEB_PORT=${WEB_PORT}|" "$root_env" && rm -f "${root_env}.bak"
else
echo "WEB_PORT=${WEB_PORT}" >> "$root_env"
fi
echo -e " ${SYM_CHECK} Web server will listen on port ${BOLD}${WEB_PORT}${RESET}"
# --- Email (optional) ---
echo ""
if confirm "Configure email notifications?" "n"; then
configure_email
else
echo -e " ${DIM} Email notifications disabled. You can configure email later via: ./setup.sh --reset-email${RESET}"
fi
echo ""
echo -e " ${BRIGHT_GREEN}${BOLD}Environment locked in.${RESET}"
}
check_encryption_key() {
local existing_enc
existing_enc=$(grep -E "^CONFIG_ENCRYPTION_KEY=" "$ENV_FILE" 2>/dev/null | head -1 | cut -d'=' -f2-)
if [[ -z "$existing_enc" ]]; then
local enc_key
enc_key=$(python3 -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())" 2>/dev/null || true)
if [[ -n "$enc_key" ]]; then
sed -i.bak "s|^CONFIG_ENCRYPTION_KEY=.*|CONFIG_ENCRYPTION_KEY=${enc_key}|" "$ENV_FILE" && rm -f "${ENV_FILE}.bak"
echo -e " ${SYM_CHECK} CONFIG_ENCRYPTION_KEY generated and saved"
fi
fi
}
# ---------------------------------------------------------------------------
# Phase 2: Build & launch containers
# ---------------------------------------------------------------------------
# Stream a docker compose build with a live progress tail
build_image() {
local service="$1"
local label="$2"
local logfile="${SETUP_LOG}.${service}"
# Stamp the image with a real version on EVERY build path (full setup,
# redeploy, and upgrade all funnel through build_image). compose passes
# ${VERSION} as the backend build-arg -> /app/VERSION -> /api/config/version,
# shown in the account-menu footer. Computed once; the export persists in this
# shell for sibling builds (e.g. the direct `compose build celery`).
# Precedence: explicit VERSION env > .vandalizer_version (image deploys) >
# git describe > "dev" when none are available (tarball / no git).
if [[ -z "${VERSION:-}" ]]; then
if [[ -f "$CODE_VERSION_FILE" ]]; then
VERSION=$(tr -d '[:space:]' < "$CODE_VERSION_FILE")
else
VERSION=$(git describe --tags --always 2>/dev/null || echo dev)
fi
export VERSION
echo -e " ${SYM_CHECK} Build version: ${BOLD}${VERSION}${RESET}"
fi
echo -e " ${SYM_NEURAL} ${BOLD}Building ${label}...${RESET}"
# Run build in background, tee to logfile
$COMPOSE_CMD build "$service" > "$logfile" 2>&1 &
local pid=$!
# Show a tail of the build output so the user sees progress
local frames=("⠋" "⠙" "⠹" "⠸" "⠼" "⠴" "⠦" "⠧" "⠇" "⠏")
local i=0
local last_line=""
while kill -0 "$pid" 2>/dev/null; do
local line
line=$(tail -1 "$logfile" 2>/dev/null | head -c 70 || true)
if [[ -n "$line" ]]; then
last_line="$line"
fi
printf "\r ${CYAN}${frames[$i]}${RESET} ${DIM}%-72s${RESET}" "$last_line"
i=$(( (i + 1) % ${#frames[@]} ))
sleep 0.15
done
if wait "$pid"; then
printf "\r ${SYM_CHECK} %-74s\n" "${label} built successfully"
cat "$logfile" >> "$SETUP_LOG"
else
printf "\r ${SYM_CROSS} %-74s\n" "${label} build failed"
echo ""
echo -e " ${DIM} Last 10 lines of build output:${RESET}"
echo -e " ${DIM} ------${RESET}"
tail -10 "$logfile" | while IFS= read -r errline; do
echo -e " ${DIM} ${errline}${RESET}"
done
echo -e " ${DIM} ------${RESET}"
cat "$logfile" >> "$SETUP_LOG"
ERRORS+=("${label} build failed — check ${SETUP_LOG}")
rm -f "$logfile"
return 1
fi
rm -f "$logfile"
}
launch_services() {
section "2" "Launching Services"
# --- Build phase: show streaming progress ---
echo -e " ${DIM} First build may take several minutes (downloading dependencies).${RESET}"
echo -e " ${DIM} Subsequent builds use Docker layer cache and are much faster.${RESET}"
echo ""
local build_ok=true
build_image "api" "Backend image (API + Celery)" || build_ok=false
# Celery shares the same Dockerfile — build its image too
echo -e " ${DIM} Building Celery from same backend image...${RESET}"
$COMPOSE_CMD build celery >> "$SETUP_LOG" 2>&1 || true
echo ""
build_image "frontend" "Frontend image (React + Nginx)" || build_ok=false
if [[ "$build_ok" == false ]]; then
echo ""
echo -e " ${SYM_CROSS} ${RED}${BOLD}One or more image builds failed. Cannot start services.${RESET}"
echo -e " ${DIM} Check the build log: ${SETUP_LOG}${RESET}"
echo ""
echo -e " ${DIM} Last 20 lines of build output:${RESET}"
tail -20 "$SETUP_LOG" | while IFS= read -r errline; do
echo -e " ${DIM} ${errline}${RESET}"
done
echo ""
return 1
fi
echo ""
echo -e " ${SYM_NEURAL} ${BOLD}Starting infrastructure layer...${RESET}"
echo ""
# Start infra first
run_step "Starting Redis" $COMPOSE_CMD up -d redis
run_step "Starting MongoDB" $COMPOSE_CMD up -d mongo
run_step "Starting ChromaDB" $COMPOSE_CMD up -d chromadb
# Wait for infra to be healthy
echo ""
echo -e " ${SYM_PULSE} ${DIM}Waiting for infrastructure health checks...${RESET}"
echo ""
local infra_ok=true
wait_healthy "redis" "Redis" 30 || infra_ok=false
wait_healthy "mongo" "MongoDB" 90 || infra_ok=false
wait_healthy "chromadb" "ChromaDB" 60 || infra_ok=false
if [[ "$infra_ok" == false ]]; then
echo ""
echo -e " ${SYM_WARN} ${YELLOW}Infrastructure not fully healthy. Retrying unhealthy services...${RESET}"
echo ""
# Restart any unhealthy infra containers and wait again
for svc in redis mongo chromadb; do
local health
health=$(compose_health "$svc")
if [[ "$health" != "healthy" && "$health" != "(healthy)" ]]; then
$COMPOSE_CMD restart "$svc" >> "$SETUP_LOG" 2>&1
fi
done
infra_ok=true
wait_healthy "redis" "Redis" 30 || infra_ok=false
wait_healthy "mongo" "MongoDB" 90 || infra_ok=false
wait_healthy "chromadb" "ChromaDB" 60 || infra_ok=false
fi
if [[ "$infra_ok" == false ]]; then
echo ""
echo -e " ${SYM_CROSS} ${RED}${BOLD}Infrastructure services are not healthy. Cannot start application layer.${RESET}"
echo -e " ${DIM} Check logs: ${COMPOSE_CMD} logs redis mongo chromadb${RESET}"
echo -e " ${DIM} Then re-run: ./setup.sh --repair${RESET}"
echo ""
return 1
fi
echo ""
echo -e " ${SYM_NEURAL} ${BOLD}Starting application layer...${RESET}"
echo ""
run_step "Starting API server" $COMPOSE_CMD up -d api
run_step "Starting Celery workers" $COMPOSE_CMD up -d celery
run_step "Starting frontend" $COMPOSE_CMD up -d frontend
# Clean up dangling images from the build
$CONTAINER_CLI image prune -f >> "$SETUP_LOG" 2>&1 || true
echo ""
echo -e " ${SYM_PULSE} ${DIM}Waiting for API to come online...${RESET}"
echo ""
wait_healthy "api" "API server" 120
wait_for_api 60
echo ""
echo -e " ${BRIGHT_GREEN}${BOLD}All systems online.${RESET}"
}
wait_healthy() {
local service="$1"
local label="$2"
local timeout="$3"
local elapsed=0
local frames=("⠋" "⠙" "⠹" "⠸" "⠼" "⠴" "⠦" "⠧" "⠇" "⠏")
local i=0
while [[ $elapsed -lt $timeout ]]; do
local health
health=$(compose_health "$service")
if [[ "$health" == "healthy" || "$health" == "(healthy)" ]]; then
printf "\r ${SYM_CHECK} %-20s ${GREEN}healthy${RESET} \n" "$label"
return 0
fi
printf "\r ${CYAN}${frames[$i]}${RESET} %-20s ${DIM}waiting... (%ds)${RESET} " "$label" "$elapsed"
i=$(( (i + 1) % ${#frames[@]} ))
sleep 1
elapsed=$((elapsed + 1))
done
printf "\r ${SYM_WARN} %-20s ${YELLOW}timeout after %ds${RESET} \n" "$label" "$timeout"
ERRORS+=("$label health check timed out")
return 1
}
wait_for_api() {
local timeout="$1"
local elapsed=0
local frames=("⠋" "⠙" "⠹" "⠸" "⠼" "⠴" "⠦" "⠧" "⠇" "⠏")
local i=0
while [[ $elapsed -lt $timeout ]]; do
if $COMPOSE_CMD exec -T api python -c \
"import urllib.request; urllib.request.urlopen('http://localhost:8001/api/health')" \
2>/dev/null; then
printf "\r ${SYM_CHECK} %-20s ${GREEN}responding${RESET} \n" "Health endpoint"
return 0
fi
printf "\r ${CYAN}${frames[$i]}${RESET} %-20s ${DIM}connecting... (%ds)${RESET} " "Health endpoint" "$elapsed"
i=$(( (i + 1) % ${#frames[@]} ))
sleep 1
elapsed=$((elapsed + 1))
done
printf "\r ${SYM_WARN} %-20s ${YELLOW}timeout${RESET} \n" "Health endpoint"
return 1
}
# ---------------------------------------------------------------------------
# Phase 3: Bootstrap admin & seed data
# ---------------------------------------------------------------------------
bootstrap() {
section "3" "Bootstrap & Identity"
echo -e " ${SYM_NEURAL} ${BOLD}Create your admin account${RESET}"
echo -e " ${DIM} This will be the first user with full system access.${RESET}"
echo ""
prompt "Admin email" "" ADMIN_EMAIL
while [[ -z "$ADMIN_EMAIL" ]]; do
echo -e " ${SYM_WARN} ${YELLOW}Email is required.${RESET}"
prompt "Admin email" "" ADMIN_EMAIL
done
prompt "Admin password" "" ADMIN_PASSWORD true
while [[ -z "$ADMIN_PASSWORD" ]]; do
echo -e " ${SYM_WARN} ${YELLOW}Password is required.${RESET}"
prompt "Admin password" "" ADMIN_PASSWORD true
done
prompt "Admin display name" "Admin" ADMIN_NAME
echo ""
echo -e " ${SYM_NEURAL} ${BOLD}Team configuration${RESET}"
echo -e " ${DIM} A default team gives all new users a shared workspace on signup.${RESET}"
echo ""
local DEFAULT_TEAM_NAME=""
if confirm "Create a shared default team?" "y"; then
prompt "Team name" "Research Administration" DEFAULT_TEAM_NAME
fi
echo ""
echo -e " ${SYM_NEURAL} ${BOLD}Institution${RESET}"
echo -e " ${DIM} Used for deployment branding and as the default institution on${RESET}"
echo -e " ${DIM} creator credits (\"by Jane Doe at <institution>\") when items are${RESET}"
echo -e " ${DIM} verified into the catalog. Leave blank to skip.${RESET}"
echo ""
local ORG_NAME=""
prompt "Institution / organization name" "" ORG_NAME
# --- Anonymous usage telemetry (opt-in) — reuse the just-entered org name ---
configure_telemetry "$ORG_NAME"
echo ""
echo -e " ${SYM_NEURAL} ${BOLD}Verified catalog${RESET}"
echo -e " ${DIM} The bootstrap will also seed research administration content:${RESET}"
echo -e " ${DIM} • Verified workflows (e.g. proposal review, compliance checks)${RESET}"
echo -e " ${DIM} • Extraction templates (structured data extraction configs)${RESET}"
echo -e " ${DIM} • Knowledge bases (source definitions — content is ingested separately)${RESET}"
echo -e " ${DIM} • Curated collections to organize the above${RESET}"
echo ""
echo -e " ${SYM_PULSE} ${DIM}Running bootstrap sequence...${RESET}"
echo ""
# Pipe credentials into the container to avoid shell expansion issues with
# special characters in passwords (e.g. $, !, \, `)
local container_name
container_name=$(compose_container api)
local bootstrap_output=""
local bootstrap_exit=1
if [[ -n "$container_name" ]]; then
# Pass credentials via stdin to Python — no shell expansion, no temp files
bootstrap_output=$(printf '%s\n' "$ADMIN_EMAIL" "$ADMIN_PASSWORD" "$ADMIN_NAME" "$DEFAULT_TEAM_NAME" "$ORG_NAME" | \
$CONTAINER_CLI exec -i "$container_name" python -c "
import sys, os, runpy
lines = sys.stdin.read().split('\n')
os.environ['ADMIN_EMAIL'] = lines[0] if len(lines) > 0 else ''
os.environ['ADMIN_PASSWORD'] = lines[1] if len(lines) > 1 else ''
os.environ['ADMIN_NAME'] = lines[2] if len(lines) > 2 else ''
os.environ['DEFAULT_TEAM_NAME'] = lines[3] if len(lines) > 3 else ''
os.environ['ORG_NAME'] = lines[4] if len(lines) > 4 else ''
runpy.run_path('bootstrap_install.py', run_name='__main__')
" 2>&1)
bootstrap_exit=$?
else
echo -e " ${SYM_CROSS} ${RED}API container not found — cannot run bootstrap${RESET}"
fi
log "Bootstrap output:"
log "$bootstrap_output"
if [[ $bootstrap_exit -ne 0 ]]; then
echo -e " ${SYM_WARN} ${YELLOW}Bootstrap exited with errors:${RESET}"
echo "$bootstrap_output" | tail -5 | while IFS= read -r errline; do
echo -e " ${DIM} ${errline}${RESET}"
done
fi
# Parse and display results
if echo "$bootstrap_output" | grep -q "Admin user created"; then
echo -e " ${SYM_CHECK} Admin account created ${DIM}(${ADMIN_EMAIL})${RESET}"
elif echo "$bootstrap_output" | grep -q "Admin user updated"; then
echo -e " ${SYM_CHECK} Admin account updated ${DIM}(${ADMIN_EMAIL})${RESET}"
elif echo "$bootstrap_output" | grep -q "Admin user already ready"; then
echo -e " ${SYM_CHECK} Admin account verified ${DIM}(${ADMIN_EMAIL})${RESET}"
else
echo -e " ${SYM_CROSS} ${RED}Admin account was NOT created${RESET}"
ERRORS+=("Admin account creation failed — re-run ./setup.sh --repair")
fi
if [[ -n "$DEFAULT_TEAM_NAME" ]]; then
if echo "$bootstrap_output" | grep -q "Default team created"; then
echo -e " ${SYM_CHECK} Default team created ${DIM}(${DEFAULT_TEAM_NAME})${RESET}"
elif echo "$bootstrap_output" | grep -q "Default team reused"; then
echo -e " ${SYM_CHECK} Default team verified ${DIM}(${DEFAULT_TEAM_NAME})${RESET}"
fi
else
echo -e " ${DIM} No default team — users will start in their personal workspace.${RESET}"
fi
# Check for catalog seeding
if echo "$bootstrap_output" | grep -qi "seed\|catalog\|workflow\|verified"; then
echo -e " ${SYM_CHECK} Verified catalog seeded"
# Extract counts from bootstrap output if available
local wf_created ss_created kb_created
wf_created=$(echo "$bootstrap_output" | grep -oi '[0-9]* workflow' | head -1 | grep -o '[0-9]*' || true)
ss_created=$(echo "$bootstrap_output" | grep -oi '[0-9]* search.set\|[0-9]* template' | head -1 | grep -o '[0-9]*' || true)
kb_created=$(echo "$bootstrap_output" | grep -oi '[0-9]* knowledge' | head -1 | grep -o '[0-9]*' || true)
[[ -n "$wf_created" ]] && echo -e " ${DIM} Workflows: ${wf_created} seeded${RESET}"
[[ -n "$ss_created" ]] && echo -e " ${DIM} Extraction templates: ${ss_created} seeded${RESET}"
[[ -n "$kb_created" ]] && echo -e " ${DIM} Knowledge bases: ${kb_created} seeded (content not yet ingested)${RESET}"