-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinstall.sh
More file actions
executable file
·1208 lines (1102 loc) · 54.3 KB
/
Copy pathinstall.sh
File metadata and controls
executable file
·1208 lines (1102 loc) · 54.3 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
#!/bin/sh
# ─────────────────────────────────────────────────────────────────────────────
# Semitexa Ultimate — one-liner installer
#
# Usage:
# curl -fsSL https://semitexa.com/install.sh | bash
# curl -fsSL https://semitexa.com/install.sh | bash -s my-project
# curl -fsSL https://semitexa.com/install.sh | bash -s my-project --start
#
# Options:
# <name> Project directory name (prompted if omitted)
# --start Auto-start server after install (non-interactive)
#
# Requirements: Docker with Compose v2 (no PHP, no Composer on host)
# Compatible: macOS, Linux, Windows (Git Bash / WSL)
# Architecture: AMD64, ARM64
#
# ── HOW TO USE SAFELY ────────────────────────────────────────────────────────
#
# BEFORE RUNNING — verify these from the directory where you want the project:
# docker info # Docker daemon must be running
# docker compose version # Must show v2 (not docker-compose v1)
#
# RECOMMENDED ONE-LINER (avoids TTY / CI hang issues):
# curl -fsSL https://semitexa.com/install.sh | bash -s my-project
#
# NON-INTERACTIVE / CI (skips all prompts, starts server immediately):
# curl -fsSL https://semitexa.com/install.sh | bash -s my-project --start
#
# WINDOWS:
# Prefer WSL2 over Git Bash — Docker socket and id -u/id -g behave
# correctly in WSL2. In Git Bash: sh install.sh my-project --start
# Line endings must be LF not CRLF, or sh will fail with obscure parse errors.
#
# PITFALLS:
# - Run from the PARENT directory of where you want the project created.
# - Edit .env only if you need local overrides before start.
# - A directory named PROJECT_NAME must not already exist.
# - SWOOLE_PORT (default 9502) must be free. Check: lsof -i :9502
# - On Docker rootless setups, ensure your user can run 'docker info'.
# - If the install is interrupted (Ctrl+C, network drop), the partial
# directory is automatically removed so you can re-run without errors.
#
# ─────────────────────────────────────────────────────────────────────────────
set -e
# set -e aborts on any non-zero exit. A partial install is worse than a clean
# failure. The last printed step number tells you exactly where it stopped.
INSTALLER_IMAGE="${SEMITEXA_INSTALLER_IMAGE:-semitexa/installer}"
# Host-side installer delegates project scaffolding to the Semitexa installer
# image. The generated project then performs dependency bootstrap in its own
# `setup` container on first `docker compose up -d`.
# ── Colour helpers ───────────────────────────────────────────────────────────
if [ -t 1 ] && command -v tput >/dev/null 2>&1; then
C_RESET="$(tput sgr0 2>/dev/null || true)"
C_GREEN="$(tput setaf 2 2>/dev/null || true)"
C_YELLOW="$(tput setaf 3 2>/dev/null || true)"
C_RED="$(tput setaf 1 2>/dev/null || true)"
C_CYAN="$(tput setaf 6 2>/dev/null || true)"
C_BOLD="$(tput bold 2>/dev/null || true)"
else
# Colour is automatically suppressed in pipes and non-TTY contexts
# (CI logs, cron, redirected output). No flags needed.
C_RESET="" C_GREEN="" C_YELLOW="" C_RED="" C_CYAN="" C_BOLD=""
fi
# tty_available: returns true if /dev/tty can actually be opened for reading.
# [ -e /dev/tty ] is NOT sufficient — the file exists even when no controlling
# terminal is attached (e.g. CI containers, tool-spawned shells), but any
# attempt to read from it then fails with "No such device or address".
# We test by actually opening the fd in a subshell; the || true keeps set -e
# from aborting the caller.
tty_available() { [ -t 0 ] || ( exec 0</dev/tty ) 2>/dev/null; }
info() { printf "%s →%s %s\n" "$C_CYAN" "$C_RESET" "$*"; }
success() { printf "%s ✓%s %s\n" "$C_GREEN" "$C_RESET" "$*"; }
warn() { printf "%s ⚠%s %s\n" "$C_YELLOW" "$C_RESET" "$*" >&2; }
error() { printf "%s ✗%s %s\n" "$C_RED" "$C_RESET" "$*" >&2; }
step() { printf "\n%s%s %s %s\n\n" "$C_BOLD" "$C_CYAN" "$*" "$C_RESET"; }
banner() {
printf "\n"
printf "%s╔══════════════════════════════════════════════════════════════╗%s\n" "$C_CYAN$C_BOLD" "$C_RESET"
printf "%s║ Semitexa Ultimate — Project Installer ║%s\n" "$C_CYAN$C_BOLD" "$C_RESET"
printf "%s║ https://semitexa.com ║%s\n" "$C_CYAN$C_BOLD" "$C_RESET"
printf "%s╚══════════════════════════════════════════════════════════════╝%s\n" "$C_CYAN$C_BOLD" "$C_RESET"
printf "\n"
}
# ── Cleanup on failure ───────────────────────────────────────────────────────
# _CLEANUP_PROJECT is armed just before we start writing files (step 3).
# It is disarmed once the install is confirmed complete (after step 5).
# On any premature exit — set -e abort, Ctrl+C, SIGTERM — the partial
# project directory is removed so the user can re-run without hitting the
# "directory already exists" guard in validate_project_name.
_CLEANUP_PROJECT=""
_on_exit() {
_p="${_CLEANUP_PROJECT:-}"
_CLEANUP_PROJECT="" # idempotent — prevents double-run if both signal + EXIT fire
if [ -n "$_p" ] && [ -d "$_p" ]; then
printf "\n" >&2
warn "Install did not complete — removing partial directory: ./${_p}"
# Docker containers can create root-owned files inside the project dir.
# Plain rm -rf fails on those.
# Fall back to a throwaway Alpine container that has root on the volume.
if ! rm -rf "$_p" 2>/dev/null; then
if command -v docker >/dev/null 2>&1; then
docker run --rm -v "$(pwd):/work" alpine \
rm -rf "/work/${_p}" 2>/dev/null \
|| warn "Could not remove '${_p}'. Run: sudo rm -rf ./${_p}"
else
warn "Could not remove '${_p}' (permission denied). Run: sudo rm -rf ./${_p}"
fi
fi
fi
}
# EXIT fires on: normal exit, set -e abort, and explicit exit N calls.
# INT/TERM are trapped separately with explicit exit codes so EXIT fires too,
# even on shells that do not propagate signal exits through the EXIT trap.
trap '_on_exit' EXIT
trap '_on_exit; exit 130' INT
trap '_on_exit; exit 143' TERM
# ── Argument parsing ─────────────────────────────────────────────────────────
# Only two inputs matter: PROJECT_NAME and --start.
# Unknown --flags warn but do NOT abort (non-fatal) — check for typos like
# --Start or --autostart if --start seems to have no effect.
PROJECT_NAME=""
AUTO_START=0
# SKIP_START is mutated by check_port_conflicts(). It MUST be declared here
# (not inside main) so check_port_conflicts can write to it and main can read
# the updated value. Calling check_port_conflicts in a subshell ($(...)) would
# isolate variable writes, causing SKIP_START to always remain 0.
SKIP_START=0
# LOCAL_DOMAIN is set by ask_local_domain() and read by print_next_steps().
# Same scope requirement as SKIP_START — must live outside both functions.
LOCAL_DOMAIN=""
# APP_REGISTERED is set to 1 by register_local_app() once the project has been
# entered into the shared local app registry (~/.semitexa/router/registry/apps)
# with a broker-allocated Swoole port written to .env. main() uses it to skip
# the legacy linear-scan check_port_conflicts: when registration succeeds, the
# port in .env is already broker-canonical and a second scan can only pick a
# port outside the broker range — corrupting cross-app uniqueness.
APP_REGISTERED=0
for _arg in "$@"; do
case "$_arg" in
--start) AUTO_START=1 ;;
--*) warn "Unknown option: $_arg (did you mean --start?)" ;;
*) [ -z "$PROJECT_NAME" ] && PROJECT_NAME="$_arg" ;;
esac
done
# ── Prerequisites ────────────────────────────────────────────────────────────
check_docker() {
# PITFALL: Docker installed but daemon not running gives a misleading
# "permission denied" on rootless Linux setups.
# Fix: systemctl start docker (or start Docker Desktop on mac/Windows).
if ! command -v docker >/dev/null 2>&1; then
error "Docker is not installed."
printf "\n Install Docker Desktop: %shttps://docs.docker.com/get-docker/%s\n\n" "$C_CYAN" "$C_RESET"
exit 1
fi
if ! docker info >/dev/null 2>&1; then
_derr="$(docker info 2>&1 || true)"
case "$_derr" in
*"permission denied"*|*"Got permission denied"*|*"connect: permission denied"*)
error "Docker permission denied."
printf " Add your user to the 'docker' group:\n"
printf " sudo usermod -aG docker \$(whoami)\n"
printf " Then log out and back in, and re-run the installer.\n"
;;
*)
error "Docker daemon is not running. Start Docker and try again."
;;
esac
exit 1
fi
# Compose v2: `docker compose` (plugin) — required.
# PITFALL: `docker-compose` (v1, standalone binary) will NOT satisfy this.
# If you have both installed, upgrade: https://docs.docker.com/compose/migrate/
if ! docker compose version >/dev/null 2>&1; then
error "Docker Compose v2 is required ('docker compose' not found)."
printf "\n Upgrade to Docker Desktop 3.6+ or install the Compose plugin:\n"
printf " %shttps://docs.docker.com/compose/install/%s\n\n" "$C_CYAN" "$C_RESET"
exit 1
fi
success "Docker $(docker --version | awk '{print $3}' | tr -d ',')" \
"/ Compose $(docker compose version --short 2>/dev/null || echo 'v2')"
}
# ── Docker permission check (Linux only) ─────────────────────────────────────
# Docker Desktop on macOS/Windows manages socket access automatically.
# On Linux, /var/run/docker.sock is owned by root:docker. The user must be in
# the 'docker' group — otherwise every docker call requires sudo, and container
# volumes produce root-owned files that break every subsequent step.
#
# Called with the script arguments ("$@") so that check_docker_permissions can
# re-exec this script via 'sg docker' after adding the user to the group,
# allowing the install to continue in the same terminal without a re-login.
check_docker_permissions() {
# macOS / Windows: Docker Desktop owns the socket — nothing to check.
_os="$(uname -s 2>/dev/null || echo Unknown)"
case "$_os" in Linux) ;; *) return ;; esac
# ── Running as root ───────────────────────────────────────────────────────
# Root can run docker, but containers create root-owned files in volumes.
# That breaks setup_env, make_bin_executable, and server:start.
if [ "$(id -u)" -eq 0 ]; then
warn "Running as root."
warn "Docker containers will create files owned by root inside ./${PROJECT_NAME:-<project>}."
warn "Recommended: use a regular user that belongs to the 'docker' group."
printf "\n"
if tty_available; then
printf " %sContinue as root anyway?%s [y/N]: " "$C_BOLD" "$C_RESET"
read -r _root_ans </dev/tty
case "$_root_ans" in
y|Y|yes|Yes|YES) return ;;
esac
info "Aborted. Re-run as a non-root user."
exit 0
fi
warn "Non-interactive: continuing as root (file ownership issues may follow)."
return
fi
# ── Docker works fine ─────────────────────────────────────────────────────
docker info >/dev/null 2>&1 && return
# ── Classify the failure ──────────────────────────────────────────────────
_derr="$(docker info 2>&1 || true)"
case "$_derr" in
*"permission denied"*|*"Got permission denied"*|*"connect: permission denied"*) ;;
*)
# Daemon not running, socket missing, etc. — let check_docker handle it.
return
;;
esac
_user="$(id -un)"
printf "\n"
error "Docker permission denied for user '${_user}'."
# ── docker group does not exist ───────────────────────────────────────────
if ! grep -q "^docker:" /etc/group 2>/dev/null && \
! getent group docker >/dev/null 2>&1; then
printf "\n"
warn "The 'docker' group does not exist — Docker may be installed incorrectly."
printf " Reinstall: %shttps://docs.docker.com/engine/install/%s\n\n" "$C_CYAN" "$C_RESET"
exit 1
fi
# ── Determine group membership ────────────────────────────────────────────
# _in_effective: user is in docker group in THIS session (id -nG shows it)
# _in_configured: user is in docker group in /etc/group (takes effect after re-login)
_in_effective=0
id -nG 2>/dev/null | tr ' ' '\n' | grep -qx "docker" && _in_effective=1
_in_configured=0
_gmembers="$(getent group docker 2>/dev/null | cut -d: -f4 \
|| grep "^docker:" /etc/group 2>/dev/null | cut -d: -f4 \
|| true)"
printf "%s" "$_gmembers" | tr ',' '\n' | grep -qx "$_user" && _in_configured=1
# ── In /etc/group but session not refreshed yet ───────────────────────────
if [ "$_in_effective" -eq 0 ] && [ "$_in_configured" -eq 1 ]; then
printf "\n"
warn "'${_user}' is already in the docker group, but this terminal session"
warn "was opened before the change took effect."
printf "\n"
printf " %sOption A%s — open a new terminal and re-run the installer.\n" \
"$C_BOLD" "$C_RESET"
if command -v sg >/dev/null 2>&1 && [ -f "$0" ]; then
printf " %sOption B%s — continue right now (activates the group in this shell):\n" \
"$C_BOLD" "$C_RESET"
printf "\n"
if tty_available; then
printf " %sContinue without re-login?%s [Y/n]: " "$C_BOLD" "$C_RESET"
read -r _sg_ans </dev/tty
case "$_sg_ans" in
n|N|no|No|NO)
info "OK. Open a new terminal and re-run the installer."
exit 1
;;
*)
info "Restarting with docker group active..."
exec sg docker -c "sh \"$0\" \"$@\""
;;
esac
fi
fi
printf "\n"
info "Open a new terminal and re-run the installer."
exit 1
fi
# ── User is NOT in the docker group at all ────────────────────────────────
printf "\n"
warn "User '${_user}' is not in the 'docker' group."
printf "\n"
printf " Without this:\n"
printf " • docker requires sudo on every call\n"
printf " • volume mounts create root-owned files (chmod/chown issues)\n"
printf " • bin/semitexa server:start will fail without sudo\n"
printf "\n"
printf " Fix: %ssudo usermod -aG docker %s%s\n" "$C_BOLD" "$_user" "$C_RESET"
printf "\n"
if ! command -v sudo >/dev/null 2>&1; then
error "'sudo' is not available on this system."
printf " As root, run: usermod -aG docker %s\n" "$_user"
printf " Then log out and back in, and re-run the installer.\n\n"
exit 1
fi
if ! tty_available; then
error "Non-interactive mode: cannot run sudo interactively."
printf " Fix manually:\n"
printf " sudo usermod -aG docker %s\n" "$_user"
printf " Then log out and back in, and re-run the installer.\n\n"
exit 1
fi
printf " %sAdd '${_user}' to the docker group now?%s (requires sudo) [Y/n]: " \
"$C_BOLD" "$C_RESET"
read -r _add_ans </dev/tty
case "$_add_ans" in
n|N|no|No|NO)
warn "Skipped. Files created by Docker containers may be owned by root."
warn "Fix later: sudo usermod -aG docker ${_user} (then re-login)"
printf "\n"
# User explicitly chose to skip — continue and let the ownership
# fix in run_create_project handle the fallout as best it can.
return
;;
esac
if ! sudo usermod -aG docker "$_user"; then
error "sudo usermod failed."
printf " Run manually: sudo usermod -aG docker %s\n" "$_user"
printf " Then log out and back in, and re-run the installer.\n\n"
exit 1
fi
success "Added '${_user}' to the 'docker' group."
printf "\n"
# Best path: re-exec this script via sg so the group is active immediately.
if command -v sg >/dev/null 2>&1 && [ -f "$0" ]; then
printf " %sContinue the installer with the new group active now?%s [Y/n]: " \
"$C_BOLD" "$C_RESET"
read -r _reexec_ans </dev/tty
case "$_reexec_ans" in
n|N|no|No|NO)
printf "\n"
info "OK. When ready:"
info " 1. Log out and back in (or open a new terminal)"
info " 2. Re-run: sh $0 $*"
printf "\n"
exit 0
;;
*)
info "Restarting with docker group active..."
exec sg docker -- sh "$0" "$@"
# exec replaces the process — lines below only run if exec fails.
warn "'sg' failed to re-exec. Open a new terminal and re-run."
exit 1
;;
esac
fi
# sg not available or running via curl|bash (no script file) — give instructions.
info "Group change saved. Apply it without logging out:"
info " newgrp docker (opens a new shell with the group active)"
printf "\n"
info "Then re-run the installer:"
if [ -f "$0" ]; then
info " sh $0 $*"
else
_rerun="curl -fsSL https://semitexa.com/install.sh | bash"
[ -n "$PROJECT_NAME" ] && _rerun="${_rerun} -s ${PROJECT_NAME}"
[ "$AUTO_START" -eq 1 ] && _rerun="${_rerun} --start"
info " ${_rerun}"
fi
printf "\n"
exit 0
}
# ── Project name ─────────────────────────────────────────────────────────────
ask_project_name() {
# When piping via `curl | bash`, stdin is the pipe, NOT your terminal.
# The script detects this and falls back to /dev/tty for interactive input.
# If /dev/tty is also unavailable (some CI containers), it defaults to
# "my-semitexa". To avoid ambiguity, always pass a name explicitly:
# curl ... | bash -s my-project
if [ -n "$PROJECT_NAME" ]; then
return
fi
# stdin may be the pipe (curl | bash) — use /dev/tty for interactive input
if tty_available; then
printf "%s Project name%s [my-semitexa]: " "$C_BOLD" "$C_RESET"
read -r PROJECT_NAME </dev/tty
PROJECT_NAME="${PROJECT_NAME:-my-semitexa}"
else
PROJECT_NAME="my-semitexa"
warn "Non-interactive mode: using default project name '${PROJECT_NAME}'."
warn "To choose a name: curl ... | bash -s <name>"
fi
}
validate_project_name() {
# ALLOWED: letters, digits, hyphens, underscores, dots.
# REJECTED: spaces, slashes, @, #, etc. — these break Docker volume mounts
# and Composer directory handling across all platforms.
case "$PROJECT_NAME" in
''|-*|*[!a-zA-Z0-9._-]*)
error "Invalid project name: '$PROJECT_NAME'. Use only letters, digits, hyphens, underscores, dots, and do not start with '-'."
exit 1 ;;
esac
# An existing directory blocks the install intentionally — this prevents
# accidentally clobbering a working project. Remove or rename it first.
# PITFALL: If a previous install failed and left a partial directory, the
# cleanup trap should have removed it automatically. If it persists (e.g.
# the trap was bypassed by SIGKILL), remove it manually: rm -rf <name>
if [ -e "$PROJECT_NAME" ]; then
error "A file or directory named '$PROJECT_NAME' already exists."
printf "\n Remove it first, or choose a different name.\n\n"
exit 1
fi
}
run_create_project() {
info "Running host-side scaffold via Docker image: ${INSTALLER_IMAGE}"
info "Refreshing installer image before scaffolding..."
if docker pull "$INSTALLER_IMAGE" >/dev/null 2>&1; then
success "Installer image refreshed."
elif docker image inspect "$INSTALLER_IMAGE" >/dev/null 2>&1; then
warn "Could not refresh ${INSTALLER_IMAGE}; using the locally cached image."
else
error "Could not pull ${INSTALLER_IMAGE}, and no local cached image is available."
exit 1
fi
mkdir -p "$PROJECT_NAME"
docker run --rm \
-v "$(pwd)/${PROJECT_NAME}:/app" \
"$INSTALLER_IMAGE" \
install
# ── Fix file ownership ─────────────────────────────────────────────────────
# The installer image runs as root (UID 0), so every file it writes to the
# volume ends up owned by root on the host — including the project directory
# itself when Docker creates it. Always chown regardless of current owner:
#
# Fix order:
# 1. Plain chown -R — works when the user already owns the socket (docker group)
# 2. Alpine container — needs only docker (no sudo), uses root inside the
# volume to chown on the host filesystem
# 3. Manual sudo hint — last resort if both above fail
_uid="$(id -u)"
_gid="$(id -g)"
info "Fixing file ownership (container writes files as root)..."
if chown -R "${_uid}:${_gid}" "$PROJECT_NAME" 2>/dev/null; then
success "Ownership fixed → $(id -un):$(id -gn)"
elif docker run --rm \
-v "$(pwd):/work" \
alpine \
chown -R "${_uid}:${_gid}" "/work/${PROJECT_NAME}" 2>/dev/null; then
success "Ownership fixed via Docker Alpine → $(id -un):$(id -gn)"
else
warn "Could not fix file ownership automatically."
warn "Run before continuing: sudo chown -R $(id -un):$(id -gn) ./${PROJECT_NAME}"
fi
}
# ── Post-install setup ───────────────────────────────────────────────────────
setup_env() {
if [ ! -f "$PROJECT_NAME/.env.default" ]; then
error "No environment baseline was generated (.env.default)."
error "The scaffold output is incomplete; aborting before later Docker/CLI steps fail."
exit 1
fi
success ".env.default created with the Semitexa local baseline"
if [ ! -f "$PROJECT_NAME/.env" ]; then
cat <<'EOF' > "$PROJECT_NAME/.env"
# Local overrides for Semitexa.
# Keep this file uncommitted.
# Add machine-specific values here when you need them.
EOF
success ".env created as a local override file"
fi
info "Edit $PROJECT_NAME/.env to override defaults when needed."
}
make_bin_executable() {
_bin="$PROJECT_NAME/bin/semitexa"
if [ -f "$_bin" ]; then
chmod +x "$_bin"
fi
# PITFALL: rsync without -p drops permissions. Fix: chmod +x bin/semitexa
# PITFALL: On Windows NTFS volumes mounted in WSL, chmod has no effect.
# Workaround: sh bin/semitexa <command> (call sh explicitly).
}
# ── Shared port helper ───────────────────────────────────────────────────────
# Reads SWOOLE_PORT from .env, then .env.default:
# - strips inline comments (SWOOLE_PORT=9502 # default → 9502)
# - strips double and single quotes
# - strips whitespace
# - validates it is a pure integer; falls back to 9502 if not
# Used by both print_next_steps and check_port_conflicts to guarantee
# they operate on the same value.
get_swoole_port() {
_p="9502"
for _env_file in "$PROJECT_NAME/.env" "$PROJECT_NAME/.env.default"; do
[ -f "$_env_file" ] || continue
_candidate="$(grep -E '^SWOOLE_PORT=' "$_env_file" 2>/dev/null \
| head -1 \
| cut -d= -f2 \
| cut -d'#' -f1 \
| tr -d "\"'" \
| tr -d ' \t' \
|| true)"
case "$_candidate" in
''|*[!0-9]*) continue ;;
*) _p="$_candidate"; break ;;
esac
done
printf "%s" "$_p"
}
# ── Port utilities ───────────────────────────────────────────────────────────
# Scan upward from PORT+1 until a port is free on both host and Docker.
# Prints the free port number, or nothing if none found within 100 tries.
find_free_port() {
_base="$1"
_try="$(expr "$_base" + 1)"
_limit="$(expr "$_base" + 100)"
while [ "$_try" -le "$_limit" ]; do
_busy=0
if command -v lsof >/dev/null 2>&1; then
lsof -i :"$_try" >/dev/null 2>&1 && _busy=1 || true
elif command -v ss >/dev/null 2>&1; then
ss -ltn 2>/dev/null | grep -qE "[: ]${_try}( |$)" && _busy=1 || true
elif command -v netstat >/dev/null 2>&1; then
netstat -ltn 2>/dev/null | grep -qE "[: ]${_try}( |$)" && _busy=1 || true
fi
if [ "$_busy" -eq 0 ] && command -v docker >/dev/null 2>&1; then
docker ps --format '{{.Ports}}' 2>/dev/null \
| grep -q ":${_try}->" && _busy=1 || true
fi
if [ "$_busy" -eq 0 ]; then
printf "%s" "$_try"
return
fi
_try="$(expr "$_try" + 1)"
done
}
# Rewrite SWOOLE_PORT in .env in-place (POSIX-safe: tmp file + mv).
update_swoole_port() {
_new="$1"
_env="${PROJECT_NAME}/.env"
_tmp="${_env}.tmp"
if [ -f "$_env" ]; then
if grep -q '^SWOOLE_PORT=' "$_env" 2>/dev/null; then
sed "s/^SWOOLE_PORT=.*/SWOOLE_PORT=${_new}/" "$_env" > "$_tmp" && mv "$_tmp" "$_env"
else
cp "$_env" "$_tmp"
printf '\nSWOOLE_PORT=%s\n' "$_new" >> "$_tmp"
mv "$_tmp" "$_env"
fi
else
printf 'SWOOLE_PORT=%s\n' "$_new" > "$_env"
fi
success "SWOOLE_PORT updated to ${_new} in .env"
}
# ── Port conflict resolution ──────────────────────────────────────────────────
# Detects port conflicts from TWO independent sources, then actively resolves
# them so the customer never has to fix anything manually:
#
# Source A — Docker-allocated ports (`docker ps`)
# The most common case in dev environments. Docker's network driver
# reserves ports through its proxy/iptables layer — they are invisible
# to lsof/ss/netstat, which is why the naive check always missed these.
#
# Source B — host-level sockets (lsof / ss / netstat)
# Processes listening directly on the host (nginx, other apps).
#
# Resolution options offered to the user:
# [1] Stop the conflicting Docker container → keep the original port
# [2] Auto-select the next free port → update .env automatically
#
# Non-interactive (no TTY): option 2 is applied silently.
#
# MUST be called directly (not in a subshell) so SKIP_START propagates.
check_port_conflicts() {
SKIP_START=0
_port="$(get_swoole_port)"
_in_use=0
_docker_owner=""
# Source A: Docker-allocated ports
if command -v docker >/dev/null 2>&1; then
_docker_owner="$(docker ps --format '{{.Names}} {{.Ports}}' 2>/dev/null \
| grep ":${_port}->" | awk '{print $1}' | head -1)"
[ -n "$_docker_owner" ] && _in_use=1
fi
# Source B: host-level sockets (fallback / belt-and-suspenders)
if [ "$_in_use" -eq 0 ]; then
if command -v lsof >/dev/null 2>&1; then
lsof -i :"$_port" >/dev/null 2>&1 && _in_use=1 || true
elif command -v ss >/dev/null 2>&1; then
ss -ltn 2>/dev/null | grep -qE "[: ]${_port}( |$)" && _in_use=1 || true
elif command -v netstat >/dev/null 2>&1; then
netstat -ltn 2>/dev/null | grep -qE "[: ]${_port}( |$)" && _in_use=1 || true
fi
fi
[ "$_in_use" -eq 0 ] && return # no conflict — nothing to do
# ── Conflict detected: resolve it ────────────────────────────────────────
_free="$(find_free_port "$_port")"
if [ -n "$_docker_owner" ]; then
warn "Port ${_port} is held by Docker container: ${_docker_owner}"
else
warn "Port ${_port} is already in use by a host process."
fi
# Non-interactive or --start: silently switch to the next free port
if ! tty_available || [ "$AUTO_START" -eq 1 ]; then
if [ -n "$_free" ]; then
info "Non-interactive: switching to port ${_free} automatically."
update_swoole_port "$_free"
# SKIP_START stays 0 — start will proceed on the new port
else
warn "Could not find a free port. Skipping server start."
SKIP_START=1
fi
return
fi
# Interactive: present options
printf "\n"
if [ -n "$_docker_owner" ]; then
printf " %s[1]%s Stop container '%s' and start on port %s\n" \
"$C_BOLD" "$C_RESET" "$_docker_owner" "$_port"
fi
if [ -n "$_free" ]; then
printf " %s[2]%s Switch to port %s — updates .env automatically\n" \
"$C_BOLD" "$C_RESET" "$_free"
fi
printf " %s[s]%s Skip — I will start manually\n" "$C_BOLD" "$C_RESET"
printf "\n"
printf " Choice: "
read -r _choice </dev/tty
case "$_choice" in
1)
if [ -n "$_docker_owner" ]; then
info "Stopping ${_docker_owner}..."
if docker stop "$_docker_owner" >/dev/null 2>&1; then
success "Container stopped. Starting on port ${_port}."
# SKIP_START stays 0
else
warn "Could not stop '${_docker_owner}'."
warn "Try manually: docker stop ${_docker_owner}"
SKIP_START=1
fi
else
warn "Option 1 is only available for Docker containers."
SKIP_START=1
fi
;;
2)
if [ -n "$_free" ]; then
update_swoole_port "$_free"
# SKIP_START stays 0 — start on the new port
else
warn "Could not find a free port automatically."
SKIP_START=1
fi
;;
*)
info "Skipping server start."
info "Run manually: cd ${PROJECT_NAME} && bin/semitexa server:start"
SKIP_START=1
;;
esac
}
# ── Local app registration ───────────────────────────────────────────────────
# Register the freshly scaffolded project in the shared local app registry
# (~/.semitexa/router/registry/apps/<uuid>.env) BEFORE the first server:start.
#
# Why this runs at install time, not at first start:
# - The broker owns Swoole port allocation in a fixed range (default
# 9501-9599) and uniqueness across every Semitexa project on this machine.
# - Without pre-registration, .env carries the scaffold default port (9502),
# and the legacy linear-scan check_port_conflicts can pick a port already
# owned by another local Semitexa app — colliding when that app starts.
# - Pre-registering guarantees this project gets a broker-canonical port
# that no other registered project can hold.
#
# `bin/semitexa local-app:register --write-env`:
# - Idempotent: keyed by absolute project_root in the registry; re-running
# reuses the existing entry instead of duplicating it.
# - Preserves the existing port if still in-range and still free.
# - Allocates a fresh port from the broker range otherwise.
# - Writes both SEMITEXA_APP_ID and SWOOLE_PORT to .env via env_upsert_kv,
# which replaces existing keys in place (no duplicate lines).
#
# --app-id is passed through when the installer scaffold pre-seeded one in
# .env, so the broker registers the SAME UUID the scaffold wrote — keeping
# .env and the broker entry coherent without a second random UUID.
#
# Failure here is non-fatal: server:start will retry the same logic via
# local_app_reconcile, so the install completes even if the registry is
# unwritable (e.g. read-only home, broker lock contention).
register_local_app() {
_bin="$PROJECT_NAME/bin/semitexa"
if [ ! -f "$_bin" ]; then
warn "bin/semitexa not found in scaffold — skipping local app registration."
warn "It will be performed on first 'bin/semitexa server:start'."
return
fi
# Reuse the SEMITEXA_APP_ID that the installer scaffold pre-seeded (when
# present) so the .env id and the broker-registered id stay aligned.
_existing_id=""
if [ -f "$PROJECT_NAME/.env" ]; then
_existing_id="$(grep -E '^SEMITEXA_APP_ID=' "$PROJECT_NAME/.env" 2>/dev/null \
| head -1 \
| cut -d= -f2- \
| tr -d "\"' " \
| tr -d '\r' \
|| true)"
fi
info "Registering app in local registry (allocates Swoole port)..."
# Stdout from local-app:register is suppressed (it duplicates the success
# line we emit below). Stderr is left visible so allocation warnings and
# broker errors still reach the user.
_rc=0
set +e
if [ -n "$_existing_id" ]; then
( cd "$PROJECT_NAME" \
&& sh ./bin/semitexa local-app:register \
"--app-id=${_existing_id}" --write-env >/dev/null )
else
( cd "$PROJECT_NAME" \
&& sh ./bin/semitexa local-app:register --write-env >/dev/null )
fi
_rc=$?
set -e
if [ "$_rc" -eq 0 ]; then
# Re-read the assigned port from .env so the user sees the canonical
# value the broker recorded (not whatever the scaffold default was).
_new_port="$(get_swoole_port)"
success "App registered → SWOOLE_PORT=${_new_port}"
APP_REGISTERED=1
else
warn "Local app registration failed (exit ${_rc})."
warn "server:start will retry via local_app_reconcile on first run."
fi
}
# ── Optional: start server ───────────────────────────────────────────────────
ask_start_server() {
# In automated pipelines (CI, Dockerfile RUN, provisioning scripts),
# always pass --start. Without it the script blocks waiting for TTY input.
if [ "$AUTO_START" -eq 1 ]; then
return 0
fi
if ! tty_available; then
info "Non-interactive mode: skipping server start. Pass --start to auto-start."
return 1
fi
printf "\n%s Start the server now?%s [Y/n]: " "$C_BOLD" "$C_RESET"
_ans="Y"
read -r _ans </dev/tty
# Empty input (Enter) defaults to YES.
# Use --start explicitly in automation to make the intent unambiguous.
case "$_ans" in
n|N|no|No|NO) return 1 ;;
*) return 0 ;;
esac
}
start_server() {
# Run in a subshell so that 'cd' is isolated. If server:start fails,
# the parent shell's working directory stays at the install root —
# no stale directory state leaks into subsequent steps or error handlers.
( cd "$PROJECT_NAME" && sh bin/semitexa server:start )
# To verify containers came up: docker compose ps
# To watch live logs: docker compose logs -f
# To stop cleanly: bin/semitexa server:stop
}
# ── Local domain setup ───────────────────────────────────────────────────────
# Converts any string into a valid RFC 1123 DNS label:
# 1. Lowercase
# 2. Replace anything not [a-z0-9-] with a hyphen
# 3. Collapse consecutive hyphens into one (--* = one or more hyphens → one)
# 4. Strip leading and trailing hyphens
# 5. Truncate to 63 chars (RFC 1035 label limit); re-strip trailing hyphen
# that truncation may expose
sanitize_for_domain() {
_s="$(printf "%s" "$1" \
| tr 'A-Z' 'a-z' \
| sed 's/[^a-z0-9-]/-/g' \
| sed 's/--*/-/g' \
| sed 's/^-*//' \
| sed 's/-*$//')"
# cut -c1-63 is POSIX and safe on empty strings
_s="$(printf "%s" "$_s" | cut -c1-63 | sed 's/-*$//')"
printf "%s" "$_s"
}
# Returns 0 (valid) or 1 (invalid) for a fully-formed domain.
# Rules enforced:
# - Must end with exactly ".test" (the only TLD allowed for local dev)
# - Label (part before .test) must be non-empty
# - Label must contain only [a-z0-9-] (already lowercased at this point)
# - Label must not start or end with a hyphen (RFC 1035 §2.3.4)
# - Label must be ≤ 63 characters (RFC 1035 §2.3.4)
validate_local_domain() {
_d="$1"
# Enforce .test suffix
case "$_d" in *.test) ;; *) return 1 ;; esac
_label="${_d%.test}"
# Non-empty
[ -z "$_label" ] && return 1
# Only [a-z0-9-]
case "$_label" in *[!a-z0-9-]*) return 1 ;; esac
# No leading or trailing hyphen
case "$_label" in -*|*-) return 1 ;; esac
# Max 63 chars — POSIX ${#var} is safe here
[ "${#_label}" -gt 63 ] && return 1
return 0
}
# Try to free a single fixed port before starting DNS services.
# Returns 0 = port is free (or was freed), 1 = still blocked.
# Checks Docker allocations first (most common case), then host sockets.
# Resolution: stop the conflicting Docker container.
# Auto mode (--start / no TTY): stops silently.
# Interactive: asks the user to confirm or skip.
_free_fixed_port() {
_ffp="$1"
_owner=""
if command -v docker >/dev/null 2>&1; then
_owner="$(docker ps --format '{{.Names}} {{.Ports}}' 2>/dev/null \
| grep ":${_ffp}[^0-9]" | awk '{print $1}' | head -1)"
[ -n "$_owner" ] || {
if command -v lsof >/dev/null 2>&1; then
lsof -i :"$_ffp" >/dev/null 2>&1 && _owner="[host process]" || true
elif command -v ss >/dev/null 2>&1; then
ss -ltn 2>/dev/null | grep -qE "[: ]${_ffp}( |$)" \
&& _owner="[host process]" || true
fi
}
fi
[ -z "$_owner" ] && return 0 # port is free
# Shared Semitexa router containers are infrastructure, not conflicts.
# They are reused across all local projects — do not stop or warn.
case "$_owner" in
semitexa-router-*) return 0 ;;
esac
warn "Port ${_ffp} is held by: ${_owner}"
if ! tty_available || [ "$AUTO_START" -eq 1 ]; then
warn "Port ${_ffp} is busy in auto mode — skipping local domain registration."
return 1
fi
printf " %s[1]%s Stop '%s' and continue\n" "$C_BOLD" "$C_RESET" "$_owner"
printf " %s[s]%s Skip domain registration (app will still start)\n" "$C_BOLD" "$C_RESET"
printf "\n Choice [1/s]: "
read -r _ffp_c </dev/tty
case "$_ffp_c" in
1)
if [ "$_owner" != "[host process]" ] \
&& docker stop "$_owner" >/dev/null 2>&1; then
success "Stopped '${_owner}'."
return 0
fi ;;
esac
return 1
}
# Calls the shared local router registration module via
# `bin/semitexa local-domain:add`.
# Non-fatal: a failure here warns the user but does NOT abort the installer.
#
# PORT GATE — all fixed ports used by the shared local router are checked
# BEFORE calling local-domain:add. If any conflict cannot be resolved we skip
# domain registration entirely, leaving LOCAL_DOMAIN="" so server:start still
# starts the app cleanly on its own port.
#
# Port 80 — shared Nginx reverse proxy
# Port 5553 — shared local DNS (dns mode only)
#
# Related commands the user can run manually inside the project directory:
# bin/semitexa local-domain:add <domain.test> — register a .test domain
# bin/semitexa local-domain:list — list registered domains
# bin/semitexa local-domain:remove <domain.test> — remove a registered domain
# bin/semitexa local-domain:mode [dns|hosts] — inspect or switch mode
register_local_domain() {
_domain="$1"
_router_mode="hosts"
_ports="80"
_dns_bin="${PROJECT_NAME}/bin/semitexa"
if [ -f "$_dns_bin" ]; then
_router_mode="$(
cd "$PROJECT_NAME" && sh ./bin/semitexa local-domain:mode 2>/dev/null || printf 'hosts'
)"
fi
if [ "$_router_mode" = "dns" ]; then
_ports="80 5553"
fi
info "Checking ports required by the shared local router (${_router_mode} mode)..."
for _dns_port in $_ports; do
if ! _free_fixed_port "$_dns_port"; then
warn "Cannot free port ${_dns_port} — skipping domain registration."
warn "App will still start on its own port."
warn "Register later: cd ${PROJECT_NAME} && bin/semitexa local-domain:add ${_domain}"
LOCAL_DOMAIN=""
return
fi
done
# ── Register ──────────────────────────────────────────────────────────────
info "Registering ${_domain} with the shared local router..."
if [ -f "$_dns_bin" ]; then
if ( cd "$PROJECT_NAME" && sh ./bin/semitexa local-domain:add "$_domain" ); then
success "Local domain registered: http://${_domain}"
info "To list domains: sh bin/semitexa local-domain:list"
info "To remove later: sh bin/semitexa local-domain:remove ${_domain}"
else
warn "Local domain registration failed — run manually once the server is up:"
warn " cd ${PROJECT_NAME} && sh bin/semitexa local-domain:add ${_domain}"
LOCAL_DOMAIN=""
fi
else
warn "bin/semitexa not found — skipping local domain registration."
warn "Register manually after start: cd ${PROJECT_NAME} && sh bin/semitexa local-domain:add ${_domain}"
LOCAL_DOMAIN=""
fi
}
# Orchestrates the full domain prompt flow.
# Sets the global LOCAL_DOMAIN variable — called directly (not in a subshell)
# so the assignment propagates to main() and print_next_steps().
#
# Behaviour by environment:
# TTY present — full interactive prompt (confirm + optional custom name)
# AUTO_START=1 — non-interactive: use generated default and register
# No TTY, no auto — skip with a tip for manual registration later
ask_local_domain() {
LOCAL_DOMAIN=""
_suggested="$(sanitize_for_domain "$PROJECT_NAME").test"
# Guard: if PROJECT_NAME sanitizes to nothing (e.g. all special chars),
# we cannot generate a safe suggestion — skip gracefully.
if [ "$_suggested" = ".test" ]; then
warn "Could not derive a safe domain from project name '${PROJECT_NAME}'."
warn "Register manually later: bin/semitexa local-domain:add <name>.test"
return
fi
# ── Non-interactive / automated path ────────────────────────────────────
# Two conditions skip the interactive prompts: