-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlds
More file actions
executable file
·3427 lines (2964 loc) · 103 KB
/
lds
File metadata and controls
executable file
·3427 lines (2964 loc) · 103 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
# Force bash even if invoked via sh
if [ -z "${BASH_VERSION:-}" ]; then exec /usr/bin/env bash "$0" "$@"; fi
# shellcheck disable=SC1090,SC2155
set -euo pipefail
###############################################################################
# 0. CORE / BOOTSTRAP-SAFE HELPERS (no Docker required)
###############################################################################
# Color defaults (overridden later by init_colors); keep safe under set -u
BOLD="${BOLD:-}"
DIM="${DIM:-}"
RED="${RED:-}"
GREEN="${GREEN:-}"
CYAN="${CYAN:-}"
YELLOW="${YELLOW:-}"
BLUE="${BLUE:-}"
MAGENTA="${MAGENTA:-}"
NC="${NC:-}"
die() {
printf "%bError:%b %s
" "${RED:-}" "${NC:-}" "$*" >&2
exit 1
}
###############################################################################
# Command presence + tool proxy rules
# - Host-only commands MUST exist on host (e.g. docker)
# - Proxy-safe tools may run from the project tools container when LDS_PROXY_TOOLS=1 and container is up
# - Anything inside `docker exec ... sh -lc '...'` must continue to use `command -v`
###############################################################################
# Cached executable lookup (host binaries only; ignores shell functions/aliases)
declare -A __LDS_HAS_BIN=()
# Back-compat: treat has_cmd as 'host binary exists' (functions/aliases do not count).
has_cmd() { has_bin "$@"; }
has_bin() {
local c="${1:-}"
[[ -n "$c" ]] || return 1
if [[ -n "${__LDS_HAS_BIN[$c]+x}" ]]; then
return "${__LDS_HAS_BIN[$c]}"
fi
type -P -- "$c" >/dev/null 2>&1
__LDS_HAS_BIN[$c]=$?
return "${__LDS_HAS_BIN[$c]}"
}
bin_path() { type -P -- "${1:?}"; }
need_bin() {
local c="${1:-}" hint="${2:-}"
has_bin "$c" && return 0
die "Missing required command: $c${hint:+ ($hint)}"
}
# Commands that must NEVER be proxied to project tools container (host control plane / privileged / filesystem)
_is_host_only_cmd() {
case "${1:-}" in
docker | sudo | su | systemctl | service | ip | iptables | nft | sysctl | mount | umount | modprobe | insmod | rmmod | rm | mv | cp | chmod | chown)
return 0
;;
esac
return 1
}
# Resolve the project-specific tools container name.
_project_tools_container() {
has_bin docker || return 1
local project ctr
project="$(lds_project)"
ctr="$(
docker ps -a \
--filter "label=com.docker.compose.project=$project" \
--filter 'label=com.docker.compose.service=server-tools' \
--format '{{.Names}}' 2>/dev/null | sed -n '1p'
)"
[[ -n "$ctr" ]] && {
printf '%s' "$ctr"
return 0
}
ctr="$(docker_compose ps -a server-tools --format '{{.Name}}' 2>/dev/null | sed -n '1p' || true)"
[[ -n "$ctr" ]] && {
printf '%s' "$ctr"
return 0
}
return 1
}
_project_tools_container_running() {
local ctr
ctr="$(_project_tools_container || true)"
[[ -n "$ctr" ]] || return 1
docker inspect -f '{{.State.Running}}' "$ctr" 2>/dev/null | grep -qx true || return 1
printf '%s' "$ctr"
}
_server_tools_running() {
[[ -n "$(_project_tools_container_running || true)" ]]
}
_server_tools_has() {
local c="${1:-}"
[[ -n "$c" ]] || return 1
local ctr
ctr="$(_project_tools_container_running || true)"
[[ -n "$ctr" ]] || return 1
"$(bin_path docker)" exec "$ctr" sh -lc "command -v \"$c\" >/dev/null 2>&1" >/dev/null 2>&1
}
# Unified command runner for proxy-safe tools
# Resolution order (your rule-set):
# 1) if cmd exists on host -> run host binary
# 2) if host-only and missing -> error
# 3) if proxy-safe and LDS_PROXY_TOOLS=1 and project tools up and cmd exists there -> run via docker exec
# 4) otherwise -> error
lds_tools_cmd() {
local cmd="${1:-}"
shift || true
[[ -n "$cmd" ]] || {
echo "lds_tools_cmd: missing command" >&2
return 2
}
# 1) host binary wins
if has_bin "$cmd"; then
local p
p="$(bin_path "$cmd")"
"$p" "$@"
return $?
fi
# 2) host-only commands must be present on host
if _is_host_only_cmd "$cmd"; then
echo "Error: '$cmd' is required on host but was not found" >&2
return 127
fi
# 3) proxy-safe tools from project tools container (opt-in)
if ((${LDS_PROXY_TOOLS:-1})); then
if ! has_bin docker; then
echo "Error: '$cmd' not available on host; tool proxy requires host 'docker'" >&2
return 127
fi
local ctr
ctr="$(_project_tools_container_running || true)"
if [[ -z "$ctr" ]]; then
echo "Error: '$cmd' not available on host and project tools container is not running (set LDS_PROXY_TOOLS=1 and start the stack)" >&2
return 127
fi
if ! _server_tools_has "$cmd"; then
echo "Error: '$cmd' not found on host nor inside project tools container" >&2
return 127
fi
local -a flags=()
[[ -t 0 ]] && flags+=(-i)
[[ -t 1 ]] && flags+=(-t)
"$(bin_path docker)" exec "${flags[@]}" "$ctr" "$cmd" "$@"
return $?
fi
# 4) not found and proxy not enabled
echo "Error: '$cmd' not available on host (set LDS_PROXY_TOOLS=1 to proxy via project tools container)" >&2
return 127
}
# Convenience wrappers for common proxy-safe tools
jq() { lds_tools_cmd jq "$@"; }
yq() { lds_tools_cmd yq "$@"; }
rg() { lds_tools_cmd rg "$@"; }
fd() { lds_tools_cmd fd "$@"; }
tree() { lds_tools_cmd tree "$@"; }
shellcheck() { lds_tools_cmd shellcheck "$@"; }
# Tool availability checks (host binary OR proxy-available)
has_tool() {
local c="${1:-}"
has_bin "$c" && return 0
_is_host_only_cmd "$c" && return 1
((${LDS_PROXY_TOOLS:-1})) || return 1
_server_tools_has "$c"
}
need_tool() {
local c="${1:-}" hint="${2:-}"
has_tool "$c" && return 0
die "Missing required command: $c${hint:+ ($hint)}"
}
###############################################################################
# Misc helpers used across the script
###############################################################################
need() {
local group found cmd
for group in "$@"; do
IFS='|,' read -ra alts <<<"$group"
found=0
for cmd in "${alts[@]}"; do
has_bin "$cmd" && {
found=1
break
}
done
((found)) && continue
local miss=${alts[*]}
miss=${miss// / or }
die "Missing command(s): $miss"
done
}
# Stream search helper: prefers ripgrep (rg) when available (host or proxied), falls back to grep.
# Reads from stdin, prints matching lines with line numbers.
text_grep() {
local ins=0
if [[ "${1:-}" == "-i" ]]; then
ins=1
shift || true
fi
local pat="${1:-}"
[[ -n "$pat" ]] || return 0
if has_tool rg; then
if ((ins)); then rg -n -i -- "$pat"; else rg -n -- "$pat"; fi
else
if ((ins)); then grep -ni -- "$pat"; else grep -n -- "$pat"; fi
fi
}
ensure_files_exist() {
local rel abs dir
for rel in "$@"; do
abs="${DIR}${rel}"
dir="${abs%/*}"
if [[ ! -d $dir ]]; then
if mkdir -p "$dir" 2>/dev/null; then
printf "%b- Created directory %s%b\n" "${YELLOW:-}" "$dir" "${NC:-}"
else
printf "%b- Warning:%b cannot create directory %s (permissions?)\n" \
"${YELLOW:-}" "${NC:-}" "$dir"
continue
fi
elif [[ ! -w $dir ]]; then
printf "%b- Warning:%b directory not writable: %s\n" "${YELLOW:-}" "${NC:-}" "$dir"
fi
if [[ -e $abs ]]; then
[[ -w $abs ]] || printf "%b- Warning:%b file not writable: %s\n" "${YELLOW:-}" "${NC:-}" "$abs"
else
if : >"$abs" 2>/dev/null; then
printf "%b- Created file %s%b\n" "${YELLOW:-}" "$abs" "${NC:-}"
else
printf "%b- Error:%b cannot create file %s (permissions?)\n" "${RED:-}" "${NC:-}" "$abs"
fi
fi
done
}
###############################################################################
# 0. BOOTSTRAP / PATHS / CONSTANTS
###############################################################################
# Resolve script directory portably (Linux/macOS/WSL)
_realpath() {
local p="$1"
if has_cmd realpath; then
realpath "$p"
return 0
fi
# GNU readlink
if readlink -f / >/dev/null 2>&1; then
readlink -f "$p"
return 0
fi
# macOS with coreutils
if has_cmd greadlink; then
greadlink -f "$p"
return 0
fi
# last resort: absolute physical dir + basename
local d b
d="$(cd -P -- "$(dirname -- "$p")" 2>/dev/null && pwd -P)" || return 1
b="$(basename -- "$p")"
printf '%s/%s\n' "$d" "$b"
}
DIR="$(dirname -- "$(_realpath "$0")")"
CFG="$DIR/docker"
ENV_MAIN="$DIR/.env"
ENV_DOCKER="$CFG/.env"
COMPOSE_FILE="$CFG/compose/main.yaml"
EXTRAS_DIR="$DIR/configuration/compose"
if [[ "${1:-}" == "--__win_workdir" ]]; then
export WORKDIR_WIN="${2:-}"
shift 2
fi
COLOR() { printf '[%sm' "$1"; }
###############################################################################
# Colors + UI (higher contrast; aligned with mkhost.sh)
###############################################################################
# Color control:
# - If stdout isn't a TTY, disable colors by default.
# - If NO_COLOR is set, disable colors.
# - Set LDS_FORCE_COLOR=1 to force colors.
_is_tty() { [[ -t 1 ]]; }
_use_color=1
if [[ "${LDS_FORCE_COLOR:-0}" != "1" ]]; then
if [[ -n "${NO_COLOR:-}" ]] || ! _is_tty; then
_use_color=0
fi
fi
if ((_use_color)); then
BOLD=$'\033[1m'
DIM=$'\033[2m'
RED=$'\033[1;31m'
GREEN=$'\033[1;32m'
CYAN=$'\033[1;36m'
YELLOW=$'\033[1;33m'
BLUE=$'\033[1;34m'
MAGENTA=$'\033[1;35m'
NC=$'\033[0m'
else
BOLD='' DIM='' RED='' GREEN='' CYAN='' YELLOW='' BLUE='' MAGENTA='' NC=''
fi
# Output control:
# - --quiet suppresses non-error output
QUIET=0
say() { ((QUIET)) || printf '%b\n' "$*"; }
ok() { ((QUIET)) || printf '%b\n' "${GREEN}$*${NC}"; }
warn() { ((QUIET)) || printf '%b\n' "${YELLOW}$*${NC}"; }
err() { printf '%b\n' "${RED}$*${NC}" >&2; }
# Default behavior: QUIET
VERBOSE=0
#───────────────────────────────────────────────────────────────────────────────
# 0a. GLOBAL ERROR HANDLER
#───────────────────────────────────────────────────────────────────────────────
command_not_found_handle() {
local unknown="$1"
[[ $unknown == cmd_* ]] && unknown=${unknown#cmd_}
printf "\n%bError:%b Unknown command '%b'\n\n" "$RED" "$NC" "$unknown"
cmd_help
exit 1
}
trap 'on_error $? $LINENO "$BASH_COMMAND"' ERR
on_error() {
local code="$1" line="$2" cmd="$3"
local fn="${FUNCNAME[1]:-main}"
local src="${BASH_SOURCE[1]:-$0}"
printf "\n%bError:%b %s:%s in %s() (exit %d)\n" "$RED" "$NC" "$src" "$line" "$fn" "$code" >&2
printf "%bCommand:%b %s\n" "$RED" "$NC" "$cmd" >&2
if ((VERBOSE)); then
printf "%bStack:%b\n" "$DIM" "$NC" >&2
local i=1
while caller "$i" >/dev/null 2>&1; do
caller "$i" >&2
i=$((i + 1))
done
fi
printf "\n" >&2
exit "$code"
}
###############################################################################
# 1a. DOCKER COMPOSE WRAPPER
###############################################################################
# ── compose extras (docker/extras/*.y{a,}ml) ────────────────────────────────
__EXTRAS_LOADED=0
declare -a __EXTRA_FILES=()
load_extras() {
# Set LDS_EXTRAS_RELOAD=1 (or global --reload-extras) to re-scan templates every call.
if [[ "${LDS_EXTRAS_RELOAD:-0}" == "1" ]]; then
__EXTRAS_LOADED=0
fi
((__EXTRAS_LOADED)) && return 0
__EXTRAS_LOADED=1
[[ -d "$EXTRAS_DIR" ]] || return 0
mapfile -t __EXTRA_FILES < <(
find "$EXTRAS_DIR" -maxdepth 1 -type f \( -name '*.yaml' -o -name '*.yml' \) -print 2>/dev/null | sort | sed '/^[[:space:]]*$/d'
)
}
docker_compose() {
load_extras
# Create required runtime files only when docker/compose operations are invoked.
((EUID == 0)) || ensure_files_exist "/docker/.env" "/configuration/php/php.ini" "/.env"
if [[ -z "${__LDS_DC_BIN:-}" ]]; then
if docker compose version >/dev/null 2>&1; then
__LDS_DC_BIN=(docker compose)
else
__LDS_DC_BIN=(docker-compose)
fi
fi
# Build -f list (stable order; later overrides earlier)
local -a extra_f=() f
for f in "${__EXTRA_FILES[@]:-}"; do
[[ -f "$f" ]] || continue
case "$f" in
*.yml | *.yaml) extra_f+=(-f "$f") ;;
esac
done
"${__LDS_DC_BIN[@]}" \
--project-directory "$DIR" \
-f "$COMPOSE_FILE" \
"${extra_f[@]}" \
--env-file "$ENV_DOCKER" \
"$@"
}
# helper: print project name
lds_project() { printf '%s' "${__LDS_PROJECT:-$(basename -- "$DIR")}"; }
# (QUIET by default) ────────────────────────────────
# Centralize quiet/verbose handling for compose subcommands.
# Usage: dc_cmd <up|pull|build> [args...]
dc_cmd() {
local sub="${1:-}"
shift || true
local -a quiet=()
if ((VERBOSE == 0)); then
case "$sub" in
up) quiet+=(--quiet-pull) ;;
pull) quiet+=(-q) ;;
build) quiet+=(--quiet) ;;
esac
fi
docker_compose "$sub" "${quiet[@]}" "$@"
}
dc_up() { dc_cmd up "$@"; }
dc_pull() { dc_cmd pull "$@"; }
dc_build() { dc_cmd build "$@"; }
# helper for our own minimal logging (still shows in quiet mode)
logv() { ((VERBOSE)) && printf "%b[%s]%b %s\n" "$CYAN" "${1:-info}" "$NC" "${2:-}" >&2 || true; }
logq() { printf "%b[%s]%b %s\n" "$CYAN" "${1:-info}" "$NC" "${2:-}" >&2; }
###############################################################################
# 1b. PROMPTS + DOTENV HELPERS
###############################################################################
# Unified prompt helper (used by env_init + profiles)
tty_readline() {
# Robust prompt/read across Linux/macOS/WSL/Windows Git Bash.
# Prefer stdin when it is a TTY (normal interactive use). If stdin is not a TTY,
# fall back to /dev/tty when available.
local __var_name="$1" __prompt="$2" __line
if [[ -t 0 ]]; then
# Interactive: show prompt on stderr (so it is never swallowed) and read stdin.
printf '%s' "$__prompt" >&2
IFS= read -r __line || return 1
elif [[ -r /dev/tty ]]; then
# Non-interactive stdin (piped) but we still have a controlling terminal.
printf '%s' "$__prompt" >/dev/tty
IFS= read -r __line </dev/tty || return 1
else
return 1
fi
printf -v "$__var_name" '%s' "$__line"
}
read_default() {
local prompt=$1 default=$2 input
tty_readline input "$(printf '%b%s [default: %s]:%b ' "$CYAN" "$prompt" "$default" "$NC")" || return 1
printf '%s' "${input:-$default}"
}
ask_yes() {
local prompt="$1" ans
tty_readline ans "$(printf '%b%s (y/n): %b' "$BLUE" "$prompt" "$NC")" || return 1
[[ "${ans,,}" == "y" ]]
}
# ── dotenv quoting: only quote when needed (spaces, tabs, #, quotes, leading/trailing whitespace) ──
env_quote() {
# Wrap in double-quotes and escape backslash + double-quote + newlines
local s=${1-}
s=${s//\\/\\\\}
s=${s//\"/\\\"}
s=${s//$'\n'/\\n}
printf '"%s"' "$s"
}
env_quote_if_needed() {
local v=${1-}
# Already quoted (single or double) => keep as-is
if [[ "$v" =~ ^\".*\"$ || "$v" =~ ^\'.*\'$ ]]; then
printf '%s' "$v"
return 0
fi
# Leading/trailing whitespace or any internal whitespace or # or quotes => quote
if [[ "$v" =~ ^[[:space:]] || "$v" =~ [[:space:]]$ || "$v" == *$'\t'* || "$v" == *" "* || "$v" == *"#"* || "$v" == *"\""* ]]; then
env_quote "$v"
return 0
fi
printf '%s' "$v"
}
# Escape replacement for sed (delimiter '|')
sed_escape_repl() {
local s=${1-}
s=${s//\\/\\\\}
s=${s//&/\\&}
s=${s//|/\\|}
printf '%s' "$s"
}
update_env() {
local file=$1 var=$2 val=${3-}
mkdir -p "$(dirname "$file")"
[[ -f "$file" ]] || {
printf "%bFile '%s' not found. Creating one.%b\n" "$YELLOW" "$file" "$NC"
: >"$file"
}
# Apply quoting only when needed (spaces etc.)
val="$(env_quote_if_needed "$val")"
# Sed-safe replacement
local val_sed
val_sed="$(sed_escape_repl "$val")"
var=$(echo "$var" | sed 's/[]\/$*.^|[]/\\&/g')
if grep -qE "^[# ]*$var=" "$file" 2>/dev/null; then
sed -Ei "s|^[# ]*($var)=.*|\1=$val_sed|" "$file"
else
printf "%s=%s\n" "$var" "$val" >>"$file"
fi
}
###############################################################################
# 1c. HTTP / WEB SERVER HELPERS
###############################################################################
http_reload() {
printf "%bReloading HTTP...%b" "$MAGENTA" "$NC"
docker ps -qf name=NGINX &>/dev/null && docker exec NGINX nginx -s reload &>/dev/null || true
docker ps -qf name=APACHE &>/dev/null && docker exec APACHE apachectl graceful &>/dev/null || true
printf "\r%bHTTP reloaded! %b\n" "$GREEN" "$NC"
}
###############################################################################
# 2. INSTALL / PERMISSIONS (HOST)
###############################################################################
add_to_windows_path() {
[[ "$OSTYPE" =~ (msys|cygwin) ]] || return 0
has_cmd cygpath || return 0
# Only add if lds.bat exists where we think it is
[[ -f "$DIR/lds.bat" ]] || return 0
local win_repo
win_repo="$(cygpath -w "$DIR")"
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "
\$t = '$win_repo'
\$cur = [Environment]::GetEnvironmentVariable('Path','User')
if ([string]::IsNullOrWhiteSpace(\$cur)) { \$cur = '' }
# Normalize (trim + case-insensitive compare) to avoid duplicates
\$parts = \$cur -split ';' | ForEach-Object { \$_.Trim() } | Where-Object { \$_ }
\$exists = \$false
foreach (\$p in \$parts) { if (\$p.ToLowerInvariant() -eq \$t.ToLowerInvariant()) { \$exists = \$true; break } }
if (-not \$exists) {
\$new = (\$parts + \$t) -join ';'
[Environment]::SetEnvironmentVariable('Path', \$new, 'User')
}
" >/dev/null 2>&1 || true
}
fix_perms() {
if [[ "$OSTYPE" =~ (msys|cygwin) ]]; then
add_to_windows_path
printf "%bWindows PATH configured.%b\n" "$GREEN" "$NC"
return 0
fi
((EUID == 0)) || die "Please run with sudo."
chmod 755 "$DIR"
chmod 2775 "$DIR/configuration"
find "$DIR/configuration" -type f ! -perm 664 -exec chmod 664 {} +
chmod 755 "$DIR/docker"
find "$DIR/docker" -type f ! -perm 644 -exec chmod 644 {} +
chmod -R 777 "$DIR/logs"
chown -R "$USER:docker" "$DIR/logs"
chmod 755 "$DIR/bin"
find "$DIR/bin" -type f -exec chmod +x {} +
chmod +x "$DIR/lds"
ln -fs "$DIR/lds" /usr/local/bin/lds
printf "%bPermissions assigned.%b\n" "$GREEN" "$NC"
}
###############################################################################
# 3. DOMAIN / PROFILE INTEGRATION
###############################################################################
mkhost() {
local ctr
ctr="$(_project_tools_container_running || true)"
[[ -n "$ctr" ]] || die "server-tools container is not running for project: $(lds_project)"
docker exec "$ctr" mkhost "$@"
}
rmhost() {
local ctr
ctr="$(_project_tools_container_running || true)"
[[ -n "$ctr" ]] || die "server-tools container is not running for project: $(lds_project)"
docker exec "$ctr" rmhost "$@"
}
setup_domain() {
local ctr
ctr="$(_project_tools_container_running || true)"
[[ -n "$ctr" ]] || die "server-tools container is not running for project: $(lds_project)"
mkhost --RESET
docker exec -it "$ctr" mkhost
local mk_state svr_prof
mk_state="$(mkhost --JSON || true)"
if has_tool jq; then
svr_prof="$(printf '%s' "$mk_state" | jq -r '.state.apache_active // empty' 2>/dev/null || true)"
else
svr_prof="$(printf '%s' "$mk_state" | tr -d '\r\n' | sed -n 's/.*"apache_active"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')"
fi
[[ -n $svr_prof ]] && modify_profiles add "$svr_prof"
mkhost --RESET
cmd_reboot
}
delete_domain() {
local ctr
ctr="$(_project_tools_container_running || true)"
[[ -n "$ctr" ]] || die "server-tools container is not running for project: $(lds_project)"
rmhost --RESET
# interactive delete
docker exec -it "$ctr" rmhost "$@"
local rm_state apache_cont
rm_state="$(rmhost --JSON || true)"
if has_tool jq; then
apache_cont="$(printf '%s' "$rm_state" | jq -r '.state.apache_delete // empty' 2>/dev/null || true)"
else
apache_cont="$(printf '%s' "$rm_state" | tr -d '\r\n' | sed -n 's/.*"apache_delete"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')"
fi
[[ -n "$apache_cont" ]] && modify_profiles remove "$apache_cont"
rmhost --RESET
cmd_reboot
}
modify_profiles() {
local action=$1
shift
local file=$ENV_DOCKER var=COMPOSE_PROFILES
local -a existing updated
if [[ -r $file ]]; then
local line value
line=$(grep -E "^${var}=" "$file" | tail -n1 || true)
value=${line#*=}
IFS=',' read -r -a existing <<<"$value"
fi
case $action in
add)
local p
for p; do
[[ -n $p && ! " ${existing[*]} " =~ " $p " ]] && updated+=("$p")
done
updated+=("${existing[@]}")
;;
remove)
local old
for old in "${existing[@]}"; do
[[ ! " $* " =~ " $old " ]] && updated+=("$old")
done
;;
*) die "modify_profiles: invalid action '$action'" ;;
esac
update_env "$file" "$var" "$(
IFS=,
echo "${updated[*]}"
)"
}
# ─────────────────────────────────────────────────────────────────────────────
# Profiles
# ─────────────────────────────────────────────────────────────────────────────
###############################################################################
# 3a. PROFILES: DEFINITIONS + SETUP FLOW
###############################################################################
declare -A SERVICES=(
[POSTGRESQL]="postgresql"
[MYSQL]="mysql"
[MARIADB]="mariadb"
[ELASTICSEARCH]="elasticsearch"
[MONGODB]="mongodb"
[REDIS]="redis"
)
declare -a SERVICE_ORDER=(POSTGRESQL MYSQL MARIADB ELASTICSEARCH MONGODB REDIS)
declare -A PROFILE_ENV=(
[elasticsearch]="ELASTICSEARCH_VERSION=9.3.0"
[mysql]="MYSQL_VERSION=latest MYSQL_ROOT_PASSWORD=12345 MYSQL_USER=infocyph MYSQL_PASSWORD=12345 MYSQL_DATABASE=localdb"
[mariadb]="MARIADB_VERSION=latest MARIADB_ROOT_PASSWORD=12345 MARIADB_USER=infocyph MARIADB_PASSWORD=12345 MARIADB_DATABASE=localdb"
[mongodb]="MONGODB_VERSION=latest MONGODB_ROOT_USERNAME=root MONGODB_ROOT_PASSWORD=12345"
[redis]="REDIS_VERSION=latest"
[postgresql]="POSTGRES_VERSION=latest POSTGRES_USER=postgres POSTGRES_PASSWORD=postgres POSTGRES_DATABASE=postgres"
)
declare -a PENDING_ENVS=()
declare -a PENDING_PROFILES=()
queue_env() { PENDING_ENVS+=("$1"); }
queue_profile() { PENDING_PROFILES+=("$1"); }
flush_envs() {
local env_file="$ENV_DOCKER" kv key val
for kv in "${PENDING_ENVS[@]}"; do
IFS='=' read -r key val <<<"$kv"
update_env "$env_file" "$key" "$val"
done
}
flush_profiles() {
local profile
for profile in "${PENDING_PROFILES[@]}"; do
modify_profiles add "$profile"
done
}
# ── setup menu (selection-first) ──────────────────────────────────────────────
setup_menu_print() {
# Print menu to stderr to avoid stdout buffering in some Windows wrappers.
{
printf "\n%bSetup profiles%b (will replace previous configuration, if exists):\n\n" "$CYAN" "$NC"
local i=1 key slug
for key in "${SERVICE_ORDER[@]}"; do
slug="${SERVICES[$key]}"
printf " %2d) %-12s (%s)\n" "$i" "$key" "$slug"
i=$((i + 1))
done
printf "\n a) ALL\n"
printf " n) NONE / Back\n\n"
} >&2
}
# Parse user selection into indices or ALL/NONE (prints one token per line)
setup_menu_parse() {
local input="${1//[[:space:]]/}"
[[ -n "$input" ]] || return 1
input="${input//;/,}"
echo "$input" | tr ',' '\n' | awk '
BEGIN { ok=1 }
/^[0-9]+-[0-9]+$/ {
split($0,a,"-")
if (a[1] > a[2]) { t=a[1]; a[1]=a[2]; a[2]=t }
for (i=a[1]; i<=a[2]; i++) print i
next
}
/^[0-9]+$/ { print $0; next }
/^[aA]$/ { print "ALL"; next }
/^[nN]$/ { print "NONE"; next }
{ ok=0 }
END { if (!ok) exit 2 }
'
}
# Outputs: newline-separated service KEYS from SERVICE_ORDER (e.g. MYSQL, REDIS)
setup_choose_services() {
local ans parsed
while :; do
setup_menu_print
tty_readline ans "Select (e.g. 1,3,5 or 2-4 or a): " || return 1
if ! parsed="$(setup_menu_parse "$ans" 2>/dev/null)"; then
printf "%bInvalid selection.%b Try again.\n" "$YELLOW" "$NC"
continue
fi
if grep -qx "NONE" <<<"$parsed"; then
return 1
fi
if grep -qx "ALL" <<<"$parsed"; then
printf "%s\n" "${SERVICE_ORDER[@]}"
return 0
fi
# Indices -> keys (de-dupe, preserve order)
local -A seen=()
local out=()
local idx key
while IFS= read -r idx; do
[[ "$idx" =~ ^[0-9]+$ ]] || continue
((idx >= 1 && idx <= ${#SERVICE_ORDER[@]})) || continue
key="${SERVICE_ORDER[idx - 1]}"
[[ -n "${seen[$key]:-}" ]] && continue
seen[$key]=1
out+=("$key")
done <<<"$parsed"
if ((${#out[@]} == 0)); then
printf "%bNo valid items selected.%b\n" "$YELLOW" "$NC"
continue
fi
printf "%s\n" "${out[@]}"
return 0
done
}
setup_service() {
local service="$1"
local profile="${SERVICES[$service]:-}"
[[ -n "$profile" ]] || die "Unknown service: $service"
printf "\n%b→ %s%b\n" "$YELLOW" "$service" "$NC"
queue_profile "$profile"
printf "%bEnter value(s) for %s:%b\n" "$BLUE" "$service" "$NC"
local pair key def val
for pair in ${PROFILE_ENV[$profile]}; do
IFS='=' read -r key def <<<"$pair"
val=$(read_default "$key" "$def")
queue_env "$key=$val"
done
}
process_all() {
local selected
if ! selected="$(setup_choose_services)"; then
printf "\n%bSetup cancelled.%b\n" "$YELLOW" "$NC"
return 0
fi
printf "\n%bWill configure:%b\n" "$CYAN" "$NC"
while IFS= read -r svc; do
printf " - %s (%s)\n" "$svc" "${SERVICES[$svc]}"
done <<<"$selected"
echo
local svc
while IFS= read -r svc; do
setup_service "$svc"
done <<<"$selected"
flush_envs
flush_profiles
printf "\n%b✅ Selected services configured!%b\n" "$GREEN" "$NC"
}
###############################################################################
# 5. ENVIRONMENT + CERT / CA
###############################################################################
detect_timezone() {
if has_cmd timedatectl; then
timedatectl show -p Timezone --value
elif [[ -n ${TZ-} ]]; then
printf '%s' "$TZ"
elif [[ -r /etc/timezone ]]; then
</etc/timezone
elif has_cmd powershell.exe; then
powershell.exe -NoProfile -Command "[System.TimeZoneInfo]::Local.Id" 2>/dev/null | tr -d '\r'
else
date +%Z
fi
}
env_init() {
local env_file="$ENV_DOCKER"
printf "%bBootstrapping environment defaults…%b\n" "$YELLOW" "$NC"
local default_tz tz
default_tz="$(detect_timezone)"
tz="$(read_default "Timezone (TZ)" "$default_tz")"
local default_git_name default_git_email git_name git_email
default_git_name="$(git config --global --get user.name 2>/dev/null || true)"
default_git_email="$(git config --global --get user.email 2>/dev/null || true)"
git_name="$(read_default "Git user.name (GIT_USER_NAME)" "$default_git_name")"
git_email="$(read_default "Git user.email (GIT_USER_EMAIL)" "$default_git_email")"
# update_env now quotes automatically when needed
update_env "$env_file" "TZ" "$tz"
update_env "$env_file" "GIT_USER_NAME" "$git_name"
update_env "$env_file" "GIT_USER_EMAIL" "$git_email"
printf "%bConfiguration saved!%b\n" "$GREEN" "$NC"
}
# ─────────────────────────────────────────────────────────────────────────────
# Root CA helpers (cross-distro)
# ─────────────────────────────────────────────────────────────────────────────
# Unique identity (avoid conflicts with other mkcert/dev CAs)
CA_BASENAME="localdevstack-rootca"
CA_NICK="LocalDevStack Root CA"
detect_os_family() {
# Output: "id|like"
# Must never fail under set -e
if [[ "${OSTYPE:-}" =~ (msys|cygwin|win32) ]]; then
echo "windows|windows"
return 0
fi
local id like
id="unknown"
like="unknown"
if [[ -r /etc/os-release ]]; then
# shellcheck disable=SC1091
. /etc/os-release || true
id="${ID:-unknown}"
like="${ID_LIKE:-unknown}"
elif has_cmd uname; then
# fallback for macOS / other unix
case "$(uname -s 2>/dev/null || true)" in
Darwin)
id="macos"
like="darwin"
;;
Linux)
id="linux"
like="linux"
;;
esac
fi
echo "$id|$like"
}
# Decide destination path + update mechanism. Echo: family|dest|updater
ca_plan() {
local os_id os_like
IFS='|' read -r os_id os_like < <(detect_os_family)
case " $os_id $os_like " in
*" debian "* | *" ubuntu "* | *" linuxmint "* | *" pop "* | *" raspbian "*)
printf "debian|/usr/local/share/ca-certificates/${CA_BASENAME}.crt|update-ca-certificates\n"
;;
*" alpine "*)
printf "alpine|/usr/local/share/ca-certificates/${CA_BASENAME}.crt|update-ca-certificates\n"
;;
*" fedora "* | *" rhel "* | *" redhat "* | *" centos "* | *" rocky "* | *" alma "* | *" amzn "* | *" amazon "* | *" sles "* | *" suse "*)
printf "rhel|/etc/pki/ca-trust/source/anchors/${CA_BASENAME}.crt|update-ca-trust\n"
;;
*" arch "* | *" manjaro "*)