-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbootstrap
More file actions
executable file
·1003 lines (918 loc) · 34 KB
/
Copy pathbootstrap
File metadata and controls
executable file
·1003 lines (918 loc) · 34 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
# scripts/bootstrap — one-command GroundControl installer
#
# Local (this machine is the VPS):
# curl -fsSL <url> | bash
#
# Remote via SSH (default agent/keys):
# curl -fsSL <url> | bash -s -- root@YOUR_IP
#
# Remote with a specific private key (like ssh -i):
# curl -fsSL <url> | bash -s -- -i ~/.ssh/id_ed25519 root@YOUR_IP
# curl -fsSL <url> | bash -s -- --identity /path/to/key -p 22 root@YOUR_IP
#
# Interactive (prompts for host / key if needed):
# curl -fsSL <url> | bash -s -- --interactive
# bash bootstrap --interactive
#
set -euo pipefail
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
YELLOW='\033[0;33m'
NC='\033[0m'
IDENTITY=""
IDENTITY_DISPLAY=""
PORT="22" # SSH port
GC_HTTP_PORT="" # Host port published for GC UI (never 80/443)
HOST=""
INTERACTIVE=0
# When set, install side-by-side at /opt/groundcontrol-bootstrap even if
# production /opt/groundcontrol already exists (never touch production).
FORCE_FRESH=0
SSH_EXTRA=()
TMP_KEY_FILE=""
# Candidate UI ports — high, uncommon, never edge 80/443
GC_PORT_CANDIDATES="3737 3847 3947 8765 9737 10037 18080 28080 38080"
# Generated per successful fresh install (printed at the end)
GC_ADMIN_EMAIL=""
GC_ADMIN_PASSWORD=""
usage() {
cat <<'USAGE'
GroundControl Bootstrap
Usage:
bash bootstrap Install on this machine
bash bootstrap user@host Install on remote via SSH
bash bootstrap -i KEY user@host Use private key file (ssh -i)
bash bootstrap -p PORT user@host SSH port (default 22)
bash bootstrap --interactive Prompt for host / key path / paste
bash bootstrap --fresh user@host Side-by-side install (never touch production)
Examples:
curl -fsSL …/bootstrap | bash -s -- -i ~/.ssh/id_ed25519 root@YOUR_IP
curl -fsSL …/bootstrap | bash -s -- --fresh -i ~/.ssh/id_ed25519 root@YOUR_IP
curl -fsSL …/bootstrap | bash -s -- --interactive
Notes:
• Use the PRIVATE key (id_ed25519), not the .pub public key
• Paths: /Users/you/.ssh/key or ~/.ssh/key or .ssh/key
• Interactive mode can paste a private key (PEM) when path resolution is hard
• If GroundControl is already healthy on the server, bootstrap leaves it alone
• --fresh installs to /opt/groundcontrol-bootstrap without touching production
• Each fresh install creates a unique login email + password for you
USAGE
}
cleanup() {
if [ -n "${TMP_KEY_FILE:-}" ] && [ -f "$TMP_KEY_FILE" ]; then
rm -f "$TMP_KEY_FILE"
fi
}
trap cleanup EXIT INT TERM
# Read a line from the real terminal even when stdin is a pipe (curl | bash).
read_tty() {
local prompt="$1"
local var=""
if [ -r /dev/tty ]; then
printf "%s" "$prompt" > /dev/tty
IFS= read -r var < /dev/tty || true
elif [ -t 0 ]; then
printf "%s" "$prompt" >&2
IFS= read -r var || true
fi
printf "%s" "$var"
}
confirm_tty() {
local prompt="$1"
local ans
ans=$(read_tty "$prompt")
case "$ans" in
y|Y|yes|YES) return 0 ;;
*) return 1 ;;
esac
}
trim() {
local s="$1"
s="${s#"${s%%[![:space:]]*}"}"
s="${s%"${s##*[![:space:]]}"}"
s="${s#\"}"
s="${s%\"}"
s="${s#\'}"
s="${s%\'}"
printf "%s" "$s"
}
# ── Unique admin credentials for each successful bootstrap ──
# Email is unique per run; password meets app policy (12+, upper, lower, digit, symbol).
generate_admin_credentials() {
local id hex1 hex2
id=$(openssl rand -hex 4 2>/dev/null || head -c 4 /dev/urandom | od -An -tx1 | tr -d ' \n')
hex1=$(openssl rand -hex 6 2>/dev/null || head -c 6 /dev/urandom | od -An -tx1 | tr -d ' \n')
hex2=$(openssl rand -hex 3 2>/dev/null || head -c 3 /dev/urandom | od -An -tx1 | tr -d ' \n')
GC_ADMIN_EMAIL="admin-${id}@groundcontrol.local"
# Prefix/suffix guarantee character classes; middle is high-entropy.
GC_ADMIN_PASSWORD="Gc-${hex1}!${hex2}A"
}
# Write install .env (session key + encryption key + admin credentials).
# Docker Compose env_file treats values literally — no shell quoting.
# Credentials are generated without spaces / $ / # so unquoted values are safe.
write_install_env() {
local dest="$1"
local jwt="$2"
local encryption_key="$3"
local email="$4"
local pass="$5"
cat > "$dest" <<EOF
JWT_SECRET=${jwt}
GROUNDCONTROL_SECRET=${encryption_key}
GC_SETUP_USERNAME=${email}
GC_SETUP_PASSWORD=${pass}
EOF
chmod 600 "$dest" 2>/dev/null || true
}
print_credentials_banner() {
local url="$1"
local email="$2"
local pass="$3"
local cred_path="${4:-}"
echo ""
echo -e "${GREEN}╔══════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║ GroundControl is ready ║${NC}"
echo -e "${GREEN}╚══════════════════════════════════════════════════╝${NC}"
echo ""
echo -e " Open: ${CYAN}${url}${NC}"
echo ""
echo -e " ${BLUE}Your login (unique for this install):${NC}"
echo -e " Email: ${CYAN}${email}${NC}"
echo -e " Password: ${CYAN}${pass}${NC}"
echo ""
echo -e " After you sign in, you'll be asked to set your own"
echo -e " email and password — keep those safe going forward."
if [ -n "$cred_path" ]; then
echo ""
echo -e " A copy was also saved on the server at:"
echo -e " ${CYAN}${cred_path}${NC}"
fi
echo ""
echo -e " ${GREEN}Your VPS now has an AI co-pilot.${NC}"
echo ""
}
# Ensure admin inside a running container (works even if image lacks ensure-admin.cjs).
# Uses base64 env to avoid shell-escaping issues with special characters.
ensure_admin_in_container() {
local container="$1"
local email="$2"
local pass="$3"
local via_remote="${4:-0}"
local b64u b64p script_b64 out
b64u=$(printf '%s' "$email" | base64 | tr -d '\n')
b64p=$(printf '%s' "$pass" | base64 | tr -d '\n')
# Plain Node script shipped as base64 so curl|bash installs need no local file.
script_b64=$(printf '%s' 'const {PrismaClient}=require("@prisma/client");
const bcrypt=require("bcryptjs");
(async () => {
const u = Buffer.from(process.env.GC_SETUP_USERNAME_B64 || "", "base64").toString("utf8").trim();
const p = Buffer.from(process.env.GC_SETUP_PASSWORD_B64 || "", "base64").toString("utf8").trim();
if (!u || !p) { console.log("MISSING"); process.exit(1); }
const prisma = new PrismaClient();
try {
if (await prisma.user.count() > 0) { console.log("EXISTS"); return; }
await prisma.user.create({
data: { username: u, password: await bcrypt.hash(p, 12), role: "admin", forcePasswordChange: true },
});
console.log("CREATED:" + u);
} finally {
await prisma.$disconnect();
}
})().catch((e) => { console.error(String((e && e.message) || e)); process.exit(1); });' | base64 | tr -d '\n')
if [ "$via_remote" = "1" ]; then
out=$(remote "echo '${script_b64}' | base64 -d > /tmp/gc-ensure-admin.cjs 2>/dev/null || echo '${script_b64}' | openssl base64 -d -A > /tmp/gc-ensure-admin.cjs
docker cp /tmp/gc-ensure-admin.cjs ${container}:/tmp/gc-ensure-admin.cjs
docker exec -e GC_SETUP_USERNAME_B64=${b64u} -e GC_SETUP_PASSWORD_B64=${b64p} ${container} node /tmp/gc-ensure-admin.cjs" 2>&1) || true
else
local tmp
tmp=$(mktemp "${TMPDIR:-/tmp}/gc-ensure-admin.XXXXXX.cjs")
printf '%s' "$script_b64" | base64 -d > "$tmp" 2>/dev/null || printf '%s' "$script_b64" | openssl base64 -d -A > "$tmp"
docker cp "$tmp" "${container}:/tmp/gc-ensure-admin.cjs" >/dev/null 2>&1 || true
rm -f "$tmp"
out=$(docker exec -e "GC_SETUP_USERNAME_B64=${b64u}" -e "GC_SETUP_PASSWORD_B64=${b64p}" "$container" node /tmp/gc-ensure-admin.cjs 2>&1) || true
fi
case "$out" in
*CREATED:*)
echo -e "${GREEN}✓ Admin account created${NC}"
return 0
;;
*EXISTS*)
echo -e "${YELLOW}! An admin account already exists — use your existing login${NC}"
return 0
;;
*)
echo -e "${YELLOW}! Could not auto-create admin yet. You can finish setup at /setup in the browser.${NC}"
if [ -n "$out" ]; then
printf '%s\n' "$out" | head -3 | sed 's/^/ /' >&2
fi
return 1
;;
esac
}
# Resolve a key path: ~/, $HOME, relative, ~/.ssh/basename, fuzzy match, warn on .pub
resolve_key_path() {
local p raw base candidates c
raw=$(trim "$1")
p="$raw"
if [ -z "$p" ]; then
printf ""
return 1
fi
case "$p" in
"~") p="${HOME}" ;;
"~/"*) p="${HOME}/${p#"~/"}" ;;
"~"*) p="${HOME}/${p#"~"}" ;;
esac
case "$p" in
"${HOME}/~/"*) p="${HOME}/${p#"${HOME}/~/"}" ;;
"${HOME}/~"*) p="${HOME}/${p#"${HOME}/~"}" ;;
esac
if [ "${p#/}" != "$p" ]; then
:
else
if [ -f "$p" ]; then
p="$(cd "$(dirname "$p")" && pwd)/$(basename "$p")"
elif [ -f "${HOME}/$p" ]; then
p="${HOME}/$p"
elif [ -f "${HOME}/.ssh/$p" ]; then
p="${HOME}/.ssh/$p"
elif [ -f "${HOME}/.ssh/$(basename "$p")" ]; then
p="${HOME}/.ssh/$(basename "$p")"
else
p="${HOME}/$p"
fi
fi
if [ "${p%.pub}" != "$p" ]; then
local priv="${p%.pub}"
if [ -f "$priv" ]; then
echo -e "${YELLOW}! That path was a public key (.pub). Using the private key: ${priv}${NC}" >&2
p="$priv"
else
echo -e "${YELLOW}! That looks like a public key (.pub). SSH needs the private key (no .pub).${NC}" >&2
echo -e " Tried: ${priv} (not found)${NC}" >&2
fi
fi
if [ -f "$p" ]; then
printf "%s" "$p"
return 0
fi
base=$(basename "$p")
base="${base%.pub}"
if [ -d "${HOME}/.ssh" ] && [ -n "$base" ]; then
candidates=""
[ -f "${HOME}/.ssh/${base}" ] && candidates="${HOME}/.ssh/${base}"
for c in "${HOME}/.ssh/"*; do
[ -f "$c" ] || continue
case "$c" in
*.pub|*.old|*.bak|*known_hosts*|*config*|*authorized_keys*) continue ;;
esac
case "$(basename "$c")" in
"${base}"*|*"${base}"*)
if [ -z "$candidates" ]; then candidates="$c"
else candidates="$candidates
$c"
fi
;;
esac
done
if [ -n "$candidates" ] && [ "$(printf '%s\n' "$candidates" | grep -c .)" -eq 1 ]; then
echo -e "${YELLOW}! Exact path missing; using closest private key: ${candidates}${NC}" >&2
printf "%s" "$candidates"
return 0
fi
if [ -n "$candidates" ]; then
echo -e "${YELLOW}! Key not found at: ${p}${NC}" >&2
echo -e " Similar private keys in ~/.ssh:${NC}" >&2
printf '%s\n' "$candidates" | while IFS= read -r c; do
echo -e " ${CYAN}$c${NC}" >&2
done
fi
fi
printf "%s" "$p"
return 1
}
write_pasted_key() {
local content="$1"
TMP_KEY_FILE=$(mktemp "${TMPDIR:-/tmp}/gc-ssh-key.XXXXXX")
printf "%s\n" "$content" > "$TMP_KEY_FILE"
chmod 600 "$TMP_KEY_FILE"
IDENTITY="$TMP_KEY_FILE"
IDENTITY_DISPLAY="(pasted private key)"
}
prompt_paste_key() {
local line body=""
echo "" > /dev/tty 2>/dev/null || true
echo -e "${BLUE}Paste your private key (including the BEGIN / END lines).${NC}" > /dev/tty 2>/dev/null || echo -e "${BLUE}Paste private key, then a line with only: END${NC}"
echo -e "When finished, type ${CYAN}END${NC} on its own line (or press Ctrl-D).${NC}" > /dev/tty 2>/dev/null || true
echo "" > /dev/tty 2>/dev/null || true
if [ -r /dev/tty ]; then
while IFS= read -r line < /dev/tty || [ -n "$line" ]; do
case "$line" in
END|end|.) break ;;
esac
body="${body}${line}
"
case "$line" in
*"END OPENSSH PRIVATE KEY"*|*"END RSA PRIVATE KEY"*|*"END EC PRIVATE KEY"*|*"END PRIVATE KEY"*)
break
;;
esac
done
else
echo -e "${RED}✗ No terminal available to paste a key.${NC}" >&2
return 1
fi
body=$(printf "%s" "$body" | sed -e 's/\r$//')
if ! printf "%s" "$body" | grep -q "BEGIN.*PRIVATE KEY"; then
echo -e "${RED}✗ That didn't look like a private key (missing BEGIN PRIVATE KEY).${NC}" >&2
echo -e " Use the private key file, not the .pub public key.${NC}" >&2
return 1
fi
write_pasted_key "$body"
echo -e "${GREEN}✓ Private key received${NC}"
return 0
}
build_ssh_base() {
SSH_EXTRA=(-o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=15 -o BatchMode=yes)
if [ -n "$PORT" ] && [ "$PORT" != "22" ]; then
SSH_EXTRA+=(-p "$PORT")
fi
if [ -n "$IDENTITY" ]; then
if [ -z "$TMP_KEY_FILE" ] || [ "$IDENTITY" != "$TMP_KEY_FILE" ]; then
local resolved
if resolved=$(resolve_key_path "$IDENTITY"); then
IDENTITY="$resolved"
IDENTITY_DISPLAY="$resolved"
else
echo -e "${RED}✗ SSH key not found: ${resolved:-$IDENTITY}${NC}" >&2
echo "" >&2
echo " Tips:" >&2
echo " • Use the private key path, e.g. ~/.ssh/id_ed25519 (not .pub)" >&2
echo " • Absolute: /Users/you/.ssh/id_ed25519" >&2
echo " • Or re-run with --interactive and choose paste" >&2
exit 1
fi
fi
chmod 600 "$IDENTITY" 2>/dev/null || true
SSH_EXTRA+=(-i "$IDENTITY" -o IdentitiesOnly=yes)
fi
}
ssh_cmd() {
# Never let ssh steal stdin when script is piped via curl | bash.
ssh -n "${SSH_EXTRA[@]}" "$@" </dev/null
}
find_free_http_port_local() {
local p used
used=$( (ss -lntH 2>/dev/null || netstat -lnt 2>/dev/null || true) | tr -s ' ' | sed -n 's/.*:\([0-9][0-9]*\) .*/\1/p' | sort -un )
for p in $GC_PORT_CANDIDATES; do
if ! printf '%s\n' "$used" | grep -qx "$p"; then
printf '%s' "$p"
return 0
fi
done
for p in $(seq 20000 20100); do
if ! printf '%s\n' "$used" | grep -qx "$p"; then
printf '%s' "$p"
return 0
fi
done
printf '28173'
}
find_free_http_port_remote() {
local p
p=$(remote "used=\$( (ss -lntH 2>/dev/null || netstat -lnt 2>/dev/null || true) | tr -s ' ' | sed -n 's/.*:\\([0-9][0-9]*\\) .*/\\1/p' | sort -un );
for p in ${GC_PORT_CANDIDATES}; do
echo \"\$used\" | grep -qx \"\$p\" && continue
echo \"\$p\"; exit 0
done
for p in \$(seq 20000 20100); do
echo \"\$used\" | grep -qx \"\$p\" && continue
echo \"\$p\"; exit 0
done
echo 28173" 2>/dev/null | tr -d '\r' | tail -1)
p=$(trim "${p:-}")
if [ -z "$p" ] || ! printf '%s' "$p" | grep -Eq '^[0-9]+$'; then
p="28173"
fi
if [ "$p" = "80" ] || [ "$p" = "443" ] || [ "$p" = "22" ]; then
p="28173"
fi
printf '%s' "$p"
}
# Fresh bootstrap compose — NEVER uses /opt/groundcontrol (production path).
# Credentials and JWT live in sibling .env (env_file).
write_bootstrap_compose_yaml() {
local http_port="$1"
cat <<EOF
# Generated by GroundControl bootstrap (side-by-side install).
# Project: gcbootstrap — does NOT manage production groundcontrol-web.
# Does NOT bind 80/443.
name: gcbootstrap
services:
app:
image: ghcr.io/teckedd-code2save/groundcontrol:latest
container_name: groundcontrol-bootstrap
restart: unless-stopped
ports:
- "${http_port}:3000"
env_file:
- .env
environment:
- NODE_ENV=production
- PORT=3000
- HOSTNAME=0.0.0.0
- DATABASE_URL=file:/app/prisma/prod.db
# Bootstrap is usually reached over plain HTTP (IP:port). Without this,
# Secure cookies are dropped by the browser and login never sticks.
- COOKIE_SECURE=false
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- gcbootstrap-db:/app/prisma
- /opt:/opt:ro
- /etc:/etc:ro
healthcheck:
test: ["CMD", "wget", "--spider", "-q", "http://127.0.0.1:3000/"]
interval: 30s
timeout: 10s
retries: 5
start_period: 25s
volumes:
gcbootstrap-db:
EOF
}
write_production_compose_yaml() {
cat <<'EOF'
# GroundControl production compose
services:
web:
image: ghcr.io/teckedd-code2save/groundcontrol:latest
container_name: groundcontrol-web
restart: unless-stopped
ports:
- "127.0.0.1:3003:3000"
env_file:
- .env
environment:
- NODE_ENV=production
- DATABASE_URL=file:/app/prisma/prod.db
volumes:
- groundcontrol-db:/app/prisma
- /var/run/docker.sock:/var/run/docker.sock
- /opt:/opt
- /etc:/etc
- /var/www:/var/www
- /root/.ssh:/root/.ssh:ro
healthcheck:
test: ["CMD", "wget", "--spider", "-q", "http://127.0.0.1:3000/"]
interval: 30s
timeout: 10s
retries: 3
start_period: 15s
volumes:
groundcontrol-db:
EOF
}
prompt_identity() {
local choice path
echo ""
echo " How do you want to provide the SSH private key?"
echo " 1) Path to key file (e.g. ~/.ssh/id_ed25519)"
echo " 2) Paste private key now"
echo " 3) Use ssh-agent / default keys only"
choice=$(read_tty "Choice [1/2/3]: ")
case "$choice" in
2|p|P|paste|Paste)
prompt_paste_key || return 1
;;
3|a|A|agent|"")
IDENTITY=""
IDENTITY_DISPLAY="(ssh-agent / defaults)"
;;
1|path|Path|*)
path=$(read_tty "Path to private key (e.g. ~/.ssh/id_ed25519): ")
path=$(trim "$path")
if [ -z "$path" ]; then
IDENTITY=""
IDENTITY_DISPLAY="(ssh-agent / defaults)"
else
resolved=""
if resolved=$(resolve_key_path "$path"); then
IDENTITY="$resolved"
IDENTITY_DISPLAY="$resolved"
echo -e "${GREEN}✓ Using key file: ${IDENTITY}${NC}"
else
echo -e "${YELLOW}! Path not found: ${resolved:-$path}${NC}"
if confirm_tty "Paste private key instead? [y/N] "; then
prompt_paste_key || return 1
else
return 1
fi
fi
fi
;;
esac
return 0
}
# Parse args
while [ $# -gt 0 ]; do
case "$1" in
-h|--help)
usage
exit 0
;;
-i|--identity|--key)
shift
IDENTITY="${1:-}"
if [ -z "$IDENTITY" ]; then
echo -e "${RED}✗ -i requires a path to a private key${NC}" >&2
exit 1
fi
shift
;;
-p|--port)
shift
PORT="${1:-22}"
shift
;;
-y|--yes)
shift
;;
--fresh|--side-by-side|--bootstrap-only)
FORCE_FRESH=1
shift
;;
--interactive|-I)
INTERACTIVE=1
shift
;;
--)
shift
break
;;
-*)
echo -e "${RED}✗ Unknown option: $1${NC}" >&2
usage
exit 1
;;
*)
if [ -z "$HOST" ]; then
HOST="$1"
else
echo -e "${YELLOW}! Ignoring extra argument: $1${NC}" >&2
fi
shift
;;
esac
done
while [ $# -gt 0 ]; do
if [ -z "$HOST" ]; then
HOST="$1"
fi
shift
done
echo ""
echo -e "${CYAN}◉ GroundControl${NC}"
echo -e " One-command install for your server"
echo ""
# Interactive: gather host / key if missing
if [ "$INTERACTIVE" -eq 1 ] || { [ -z "$HOST" ] && [ -r /dev/tty ] && confirm_tty "Install on a remote VPS via SSH? [y/N] "; }; then
if [ -z "$HOST" ]; then
HOST=$(read_tty "SSH target (user@host): ")
HOST=$(trim "$HOST")
fi
if [ -z "$HOST" ]; then
echo -e "${BLUE}→ No host given — installing on this machine.${NC}"
else
PORT_IN=$(read_tty "SSH port [${PORT}]: ")
PORT_IN=$(trim "$PORT_IN")
if [ -n "$PORT_IN" ]; then
PORT="$PORT_IN"
fi
if [ -z "$IDENTITY" ]; then
prompt_identity || exit 1
fi
fi
INTERACTIVE=1
fi
if [ -z "$HOST" ]; then
# ── Local install ─────────────────────────────────────
echo -e "${BLUE}→ Installing on this machine...${NC}"
echo ""
OS_ID=$(grep ^ID= /etc/os-release 2>/dev/null | cut -d= -f2 | tr -d '"' || echo 'unknown')
echo -e "${GREEN}✓ Server OS: ${OS_ID}${NC}"
if docker --version >/dev/null 2>&1; then
echo -e "${GREEN}✓ Docker is ready${NC}"
else
echo -e "${BLUE}→ Installing Docker...${NC}"
curl -fsSL https://get.docker.com | sh || {
echo -e "${RED}✗ Docker install failed${NC}"
exit 1
}
echo -e "${GREEN}✓ Docker installed${NC}"
fi
# Never clobber production /opt/groundcontrol
if [ -f /opt/groundcontrol/docker-compose.yml ] && grep -q 'groundcontrol-web\|container_name: groundcontrol-web' /opt/groundcontrol/docker-compose.yml 2>/dev/null; then
echo -e "${YELLOW}! GroundControl is already installed at /opt/groundcontrol.${NC}"
echo -e " Open your existing site, or manage it with:"
echo -e " ${CYAN}cd /opt/groundcontrol && docker compose up -d${NC}"
exit 0
fi
echo -e "${BLUE}→ Preparing GroundControl...${NC}"
GC_HTTP_PORT=$(find_free_http_port_local)
JWT_SECRET=$(openssl rand -hex 32 2>/dev/null || head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')
GROUNDCONTROL_SECRET=$(openssl rand -hex 32 2>/dev/null || head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')
generate_admin_credentials
echo -e "${GREEN}✓ UI will be available on port ${GC_HTTP_PORT}${NC}"
mkdir -p /opt/groundcontrol-bootstrap
write_install_env /opt/groundcontrol-bootstrap/.env "$JWT_SECRET" "$GROUNDCONTROL_SECRET" "$GC_ADMIN_EMAIL" "$GC_ADMIN_PASSWORD"
write_bootstrap_compose_yaml "$GC_HTTP_PORT" > /opt/groundcontrol-bootstrap/docker-compose.yml
# Credentials file for the operator (same as printed)
{
echo "GroundControl admin login"
echo "Email: ${GC_ADMIN_EMAIL}"
echo "Password: ${GC_ADMIN_PASSWORD}"
echo ""
echo "Sign in, then update your email and password when prompted."
echo "Generated: $(date -u +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date)"
} > /opt/groundcontrol-bootstrap/ADMIN_CREDENTIALS.txt
chmod 600 /opt/groundcontrol-bootstrap/ADMIN_CREDENTIALS.txt 2>/dev/null || true
cd /opt/groundcontrol-bootstrap
if docker compose version >/dev/null 2>&1; then
docker compose -p gcbootstrap up -d --pull always
else
docker-compose -p gcbootstrap up -d
fi
echo -e "${BLUE}→ Starting GroundControl...${NC}"
# Wait for app so we can create the admin account
ready=0
for i in 1 2 3 4 5 6 7 8 9 10; do
sleep 2
if wget -qO- --timeout=3 "http://127.0.0.1:${GC_HTTP_PORT}/" >/dev/null 2>&1 \
|| curl -sf --max-time 3 "http://127.0.0.1:${GC_HTTP_PORT}/" >/dev/null 2>&1; then
ready=1
break
fi
done
if [ "$ready" -eq 1 ]; then
echo -e "${GREEN}✓ GroundControl is online${NC}"
else
echo -e "${YELLOW}! Still starting — creating your account next${NC}"
fi
# Prefer entrypoint-created account; always try docker exec so current images work
ensure_admin_in_container "groundcontrol-bootstrap" "$GC_ADMIN_EMAIL" "$GC_ADMIN_PASSWORD" 0 || true
print_credentials_banner \
"http://localhost:${GC_HTTP_PORT}" \
"$GC_ADMIN_EMAIL" \
"$GC_ADMIN_PASSWORD" \
"/opt/groundcontrol-bootstrap/ADMIN_CREDENTIALS.txt"
exit 0
fi
# ── Remote install via SSH ──────────────────────────────
remote() {
ssh_cmd "$HOST" "$@"
return $?
}
remote_ok() {
remote "$@" >/dev/null 2>&1
}
echo -e " Server: ${BLUE}${HOST}${NC}"
if [ -n "${IDENTITY_DISPLAY:-$IDENTITY}" ]; then
echo -e " Key: ${BLUE}${IDENTITY_DISPLAY:-$IDENTITY}${NC}"
fi
if [ "$PORT" != "22" ]; then
echo -e " Port: ${BLUE}${PORT}${NC}"
fi
echo ""
build_ssh_base
echo -e "${BLUE}→ Connecting to your server...${NC}"
if ! remote_ok "echo ok"; then
echo -e "${YELLOW}! Could not connect with the current credentials.${NC}"
if { [ -r /dev/tty ] || [ -t 0 ]; }; then
echo ""
echo " If you usually run:"
echo -e " ${CYAN}ssh -i ~/.ssh/your_private_key ${HOST}${NC}"
echo " use that same private key (not the .pub), or paste the key."
echo ""
if [ -z "$IDENTITY" ] || [ ! -f "$IDENTITY" ]; then
IDENTITY=""
TMP_KEY_FILE=""
prompt_identity || exit 1
fi
build_ssh_base
if remote_ok "echo ok"; then
echo -e "${GREEN}✓ Connected${NC}"
else
echo -e "${RED}✗ Still cannot reach ${HOST}${NC}"
echo ""
echo " Check that:"
echo " 1. The host is online and reachable"
echo " 2. You used the private key (file without .pub)"
echo " 3. Manual test: ssh -i ${IDENTITY:-~/.ssh/id_ed25519} -p ${PORT} ${HOST}"
echo " 4. Install your public key: ssh-copy-id -i KEY.pub ${HOST}"
exit 1
fi
else
echo -e "${RED}✗ Cannot reach ${HOST}${NC}"
echo ""
echo " Pass a private key explicitly:"
echo -e " ${CYAN}curl -fsSL https://raw.githubusercontent.com/teckedd-code2save/groundcontrol/main/scripts/bootstrap | bash -s -- -i ~/.ssh/id_ed25519 ${HOST}${NC}"
echo " Or: bash -s -- --interactive (path or paste)"
exit 1
fi
else
echo -e "${GREEN}✓ Connected${NC}"
fi
echo -e "${BLUE}→ Checking server environment...${NC}"
OS_ID=$(remote "cat /etc/os-release 2>/dev/null | grep ^ID= | head -1 | cut -d= -f2 | tr -d '\"'" 2>/dev/null || true)
OS_ID=$(trim "${OS_ID:-}")
if [ -z "$OS_ID" ]; then
OS_ID="unknown"
fi
echo -e "${GREEN}✓ Server OS: ${OS_ID}${NC}"
echo -e "${BLUE}→ Checking Docker...${NC}"
if remote_ok "command -v docker >/dev/null 2>&1 && docker --version >/dev/null 2>&1"; then
echo -e "${GREEN}✓ Docker is ready${NC}"
else
echo -e "${BLUE}→ Installing Docker...${NC}"
if ! remote "curl -fsSL https://get.docker.com | sh"; then
echo -e "${RED}✗ Docker install failed${NC}"
exit 1
fi
remote "command -v systemctl >/dev/null 2>&1 && systemctl enable --now docker 2>/dev/null || service docker start 2>/dev/null || true" || true
echo -e "${GREEN}✓ Docker installed${NC}"
fi
# ── Existing production install at /opt/groundcontrol ──
# Default: if production is healthy, leave it alone (no rewrite / pull / recreate).
# Only repair when the install is clearly broken. Use --fresh for a side-by-side
# install that never touches /opt/groundcontrol.
echo -e "${BLUE}→ Looking for an existing GroundControl install...${NC}"
HAS_PROD_DIR=0
HAS_PROD_ENV=0
HAS_PROD_COMPOSE=0
PROD_HEALTHY=0
PROD_RUNNING=0
remote_ok "test -d /opt/groundcontrol" && HAS_PROD_DIR=1
remote_ok "test -f /opt/groundcontrol/.env" && HAS_PROD_ENV=1
remote_ok "test -f /opt/groundcontrol/docker-compose.yml" && HAS_PROD_COMPOSE=1
remote_ok "docker ps --format '{{.Names}}' 2>/dev/null | grep -qx groundcontrol-web" && PROD_RUNNING=1
remote_ok "wget -qO- --timeout=4 http://127.0.0.1:3003/ >/dev/null 2>&1 || curl -sf --max-time 4 http://127.0.0.1:3003/ >/dev/null" && PROD_HEALTHY=1
if [ "$FORCE_FRESH" -eq 1 ]; then
echo -e "${BLUE}→ --fresh: installing side-by-side (will not modify /opt/groundcontrol)${NC}"
elif [ "$PROD_HEALTHY" -eq 1 ] || { [ "$PROD_RUNNING" -eq 1 ] && [ "$HAS_PROD_COMPOSE" -eq 1 ]; }; then
# Already installed and working — do not pull, rewrite, or recreate.
HOST_IP=$(echo "$HOST" | sed 's/.*@//')
echo -e "${GREEN}✓ GroundControl is already installed and running${NC}"
echo ""
echo -e "${GREEN}╔══════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║ Already installed — nothing changed ║${NC}"
echo -e "${GREEN}╚══════════════════════════════════════════════════╝${NC}"
echo ""
echo -e " Path: ${CYAN}/opt/groundcontrol${NC}"
echo -e " Proxy: ${CYAN}127.0.0.1:3003${NC} (Caddy/Nginx → this)"
echo -e " Container:${CYAN}groundcontrol-web${NC}"
if [ "$PROD_HEALTHY" -eq 1 ]; then
echo -e " Status: ${GREEN}healthy${NC}"
else
echo -e " Status: container is up (HTTP check pending)"
fi
echo ""
echo -e " Sign in with the account you already use on this server."
echo -e " Bootstrap did ${YELLOW}not${NC} restart or rewrite your install."
echo ""
echo -e " Want a separate trial install instead?"
echo -e " ${CYAN}curl -fsSL …/bootstrap | bash -s -- --fresh -i KEY ${HOST}${NC}"
echo ""
exit 0
elif [ "$HAS_PROD_DIR" -eq 1 ] || [ "$HAS_PROD_ENV" -eq 1 ] || [ "$HAS_PROD_COMPOSE" -eq 1 ]; then
# Production path exists but is not healthy — repair carefully.
echo -e "${YELLOW}! Found /opt/groundcontrol but it is not healthy — repairing only what is needed${NC}"
# Ensure .env secrets without clobbering existing values
remote "mkdir -p /opt/groundcontrol
cd /opt/groundcontrol
if [ ! -f .env ]; then
touch .env
fi
if ! grep -q '^JWT_SECRET=' .env 2>/dev/null; then
echo \"JWT_SECRET=\$(openssl rand -hex 32 2>/dev/null || head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \\n')\" >> .env
fi
if ! grep -q '^HOST_PORT=' .env 2>/dev/null; then
echo 'HOST_PORT=3003' >> .env
fi" || true
# Only rewrite compose when missing or clearly not production (no groundcontrol-web)
NEEDS_COMPOSE=0
if [ "$HAS_PROD_COMPOSE" -eq 0 ]; then
NEEDS_COMPOSE=1
elif ! remote_ok "grep -q 'groundcontrol-web' /opt/groundcontrol/docker-compose.yml"; then
NEEDS_COMPOSE=1
echo -e "${YELLOW}! Compose file does not look like production — restoring production layout${NC}"
fi
if [ "$NEEDS_COMPOSE" -eq 1 ]; then
PROD_B64=$(write_production_compose_yaml | base64 | tr -d '\n')
if ! remote "echo '${PROD_B64}' | base64 -d > /opt/groundcontrol/docker-compose.yml"; then
remote "echo '${PROD_B64}' | openssl base64 -d -A > /opt/groundcontrol/docker-compose.yml" || {
echo -e "${RED}✗ Could not write production docker-compose.yml${NC}"
exit 1
}
fi
fi
# Start without --pull always (avoid surprise upgrades during bootstrap)
# Do not compose down first — that recreated networks and disrupted a healthy history.
echo -e "${BLUE}→ Starting production container (no image pull)...${NC}"
if ! remote "cd /opt/groundcontrol && (docker compose up -d || docker-compose up -d)"; then
echo -e "${RED}✗ Failed to start GroundControl${NC}"
remote "cd /opt/groundcontrol && docker compose logs --tail=50" || true
exit 1
fi
if remote_ok "sleep 3; wget -qO- --timeout=5 http://127.0.0.1:3003/ >/dev/null 2>&1 || curl -sf --max-time 5 http://127.0.0.1:3003/ >/dev/null"; then
echo -e "${GREEN}✓ GroundControl is online${NC}"
else
echo -e "${YELLOW}! Started, but the health check is still warming up${NC}"
fi
echo ""
echo -e "${GREEN}╔══════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║ GroundControl is ready ║${NC}"
echo -e "${GREEN}╚══════════════════════════════════════════════════╝${NC}"
echo ""
echo -e " Path: ${CYAN}/opt/groundcontrol${NC}"
echo -e " Proxy: ${CYAN}127.0.0.1:3003${NC}"
echo ""
echo -e " Sign in with the account you already created."
echo -e " For a brand-new side-by-side install: add ${CYAN}--fresh${NC}"
echo ""
exit 0
fi
# ── Fresh install: side-by-side dir, never production path ──
if [ "$FORCE_FRESH" -eq 1 ]; then
echo -e "${BLUE}→ Side-by-side install into /opt/groundcontrol-bootstrap...${NC}"
else
echo -e "${BLUE}→ Installing GroundControl...${NC}"
fi
GC_HTTP_PORT=$(find_free_http_port_remote)
JWT_SECRET=$(openssl rand -hex 32 2>/dev/null || head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')
GROUNDCONTROL_SECRET=$(openssl rand -hex 32 2>/dev/null || head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')
generate_admin_credentials
echo -e "${GREEN}✓ UI will be available on port ${GC_HTTP_PORT}${NC}"
if ! remote "mkdir -p /opt/groundcontrol-bootstrap"; then
echo -e "${RED}✗ Could not create /opt/groundcontrol-bootstrap${NC}"
exit 1
fi
# Write .env on remote (credentials + session/encryption keys) — unquoted Compose env_file format
ENV_CONTENT=$(printf 'JWT_SECRET=%s\nGROUNDCONTROL_SECRET=%s\nGC_SETUP_USERNAME=%s\nGC_SETUP_PASSWORD=%s\n' \
"$JWT_SECRET" "$GROUNDCONTROL_SECRET" "$GC_ADMIN_EMAIL" "$GC_ADMIN_PASSWORD")
ENV_B64=$(printf '%s' "$ENV_CONTENT" | base64 | tr -d '\n')
if ! remote "echo '${ENV_B64}' | base64 -d > /opt/groundcontrol-bootstrap/.env && chmod 600 /opt/groundcontrol-bootstrap/.env"; then
remote "echo '${ENV_B64}' | openssl base64 -d -A > /opt/groundcontrol-bootstrap/.env && chmod 600 /opt/groundcontrol-bootstrap/.env" || {
echo -e "${RED}✗ Could not write install environment${NC}"
exit 1
}
fi
COMPOSE_B64=$(write_bootstrap_compose_yaml "$GC_HTTP_PORT" | base64 | tr -d '\n')
if ! remote "echo '${COMPOSE_B64}' | base64 -d > /opt/groundcontrol-bootstrap/docker-compose.yml"; then
if ! remote "echo '${COMPOSE_B64}' | openssl base64 -d -A > /opt/groundcontrol-bootstrap/docker-compose.yml 2>/dev/null"; then
echo -e "${RED}✗ Could not write docker-compose.yml${NC}"
exit 1
fi
fi
# Save credentials on the server
CRED_CONTENT=$(cat <<EOF
GroundControl admin login
Email: ${GC_ADMIN_EMAIL}
Password: ${GC_ADMIN_PASSWORD}
Sign in, then update your email and password when prompted.
Generated: $(date -u +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date)
EOF
)
CRED_B64=$(printf '%s' "$CRED_CONTENT" | base64 | tr -d '\n')
remote "echo '${CRED_B64}' | base64 -d > /opt/groundcontrol-bootstrap/ADMIN_CREDENTIALS.txt && chmod 600 /opt/groundcontrol-bootstrap/ADMIN_CREDENTIALS.txt" || true
echo -e "${BLUE}→ Starting GroundControl...${NC}"
if ! remote "cd /opt/groundcontrol-bootstrap && (docker compose -p gcbootstrap up -d --pull always || docker-compose -p gcbootstrap up -d)"; then
echo -e "${RED}✗ Failed to start GroundControl${NC}"
remote "cd /opt/groundcontrol-bootstrap && docker compose -p gcbootstrap logs --tail=40" || true
exit 1
fi
echo -e "${BLUE}→ Waiting for GroundControl to come online...${NC}"
ready=0
for i in 1 2 3 4 5 6 7 8 9 10 11 12; do
if remote_ok "wget -qO- --timeout=4 http://127.0.0.1:${GC_HTTP_PORT}/ >/dev/null 2>&1 || curl -sf --max-time 4 http://127.0.0.1:${GC_HTTP_PORT}/ >/dev/null"; then
ready=1
break
fi
sleep 2
done
if [ "$ready" -eq 1 ]; then
echo -e "${GREEN}✓ GroundControl is online${NC}"
else
echo -e "${YELLOW}! Still starting — creating your account next${NC}"
fi
# Create admin even if the image hasn't been rebuilt with entrypoint seed yet
ensure_admin_in_container "groundcontrol-bootstrap" "$GC_ADMIN_EMAIL" "$GC_ADMIN_PASSWORD" 1 || true
HOST_IP=$(echo "$HOST" | sed 's/.*@//')
print_credentials_banner \
"http://${HOST_IP}:${GC_HTTP_PORT}" \
"$GC_ADMIN_EMAIL" \