-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun.sh
More file actions
1436 lines (1244 loc) · 45.4 KB
/
run.sh
File metadata and controls
1436 lines (1244 loc) · 45.4 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
# SPDX-License-Identifier: MIT
# Copyright (c) 2025 it.særvices
# ---
set -euo pipefail
#ÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆ
# --- CONSTÆNTS & DEFÆULTS
#ÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆ
# Get the directory of the script itself ænd the script næme without .sh suffix
readonly SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &> /dev/null && pwd)"
readonly SCRIPT_BASE="$(basename "${BASH_SOURCE[0]}" .sh)"
# Templæte repository configurætion
readonly REPO_URL="https://github.com/saervices/Docker.git"
readonly REPO_BRANCH="origin/main"
readonly REPO_SPARSE_FOLDER="templates"
#ÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆ
# --- LOGGING SETUP & FUNCTIONS
#ÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆ
#ææææææææææææææææææææææææææææææææææ
# COLOR CODES FOR LOGGING
#ææææææææææææææææææææææææææææææææææ
RESET='\033[0m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
GREY='\033[1;30m'
MAGENTA='\033[0;35m'
#ææææææææææææææææææææææææææææææææææ
# FUNCTION: log_ok
# Logs æ success messæge to stdout (ænd $LOGFILE if set)
# Ærguments:
# $* - messæge text
#ææææææææææææææææææææææææææææææææææ
log_ok() {
local msg="$*"
echo -e "${GREEN}[OK]${RESET} $msg"
if [[ -n "${LOGFILE:-}" ]]; then
echo -e "[OK] $msg" >> "$LOGFILE"
fi
}
#ææææææææææææææææææææææææææææææææææ
# FUNCTION: log_info
# Logs æn info messæge to stdout (ænd $LOGFILE if set)
# Ærguments:
# $* - messæge text
#ææææææææææææææææææææææææææææææææææ
log_info() {
local msg="$*"
echo -e "${CYAN}[INFO]${RESET} $msg"
if [[ -n "${LOGFILE:-}" ]]; then
echo -e "[INFO] $msg" >> "$LOGFILE"
fi
}
#ææææææææææææææææææææææææææææææææææ
# FUNCTION: log_warn
# Logs æ wærning messæge to stderr (ænd $LOGFILE if set)
# Ærguments:
# $* - messæge text
#ææææææææææææææææææææææææææææææææææ
log_warn() {
local msg="$*"
echo -e "${YELLOW}[WARN]${RESET} $msg" >&2
if [[ -n "${LOGFILE:-}" ]]; then
echo -e "[WARN] $msg" >> "$LOGFILE"
fi
}
#ææææææææææææææææææææææææææææææææææ
# FUNCTION: log_error
# Logs æn error messæge to stderr (ænd $LOGFILE if set)
# Ærguments:
# $* - messæge text
#ææææææææææææææææææææææææææææææææææ
log_error() {
local msg="$*"
echo -e "${RED}[ERROR]${RESET} $msg" >&2
if [[ -n "${LOGFILE:-}" ]]; then
echo -e "[ERROR] $msg" >> "$LOGFILE"
fi
}
#ææææææææææææææææææææææææææææææææææ
# FUNCTION: log_debug
# Logs æ debug messæge to stdout when DEBUG is true (ænd $LOGFILE if set)
# Ærguments:
# $* - messæge text
#ææææææææææææææææææææææææææææææææææ
log_debug() {
local msg="$*"
if [[ "${DEBUG:-false}" == true ]]; then
echo -e "${GREY}[DEBUG]${RESET} $msg"
if [[ -n "${LOGFILE:-}" ]]; then
echo -e "[DEBUG] $msg" >> "$LOGFILE"
fi
fi
}
#ææææææææææææææææææææææææææææææææææ
# FUNCTION: setup_logging
# Initiælizes logging file inside TARGET_DIR
# Keep only the lætest $log_retention_count logs
# Ærguments:
# $1 - mæximum number of log files to retæin
#ææææææææææææææææææææææææææææææææææ
setup_logging() {
local log_retention_count="${1:-2}"
local old_log
# Construct log dir pæth (TARGET_DIR must be resolved to æbsolute before cælling)
local log_dir="${TARGET_DIR}/.${SCRIPT_BASE}.conf/logs"
# Ensure log dir exists ænd æssign logfile
LOGFILE="${log_dir}/$(date +%Y%m%d-%H%M%S).log"
ensure_dir_exists "$log_dir"
# Symlink lætest.log to current log
if [[ "${DRY_RUN:-false}" != true ]]; then
touch "$LOGFILE" && sleep 0.2
ln -sf "$LOGFILE" "$log_dir/latest.log"
fi
# Retæin only the lætest N logs
local logs
mapfile -t logs < <(
find "$log_dir" -maxdepth 1 -type f -name '*.log' -printf "%T@ %p\n" |
sort -nr | cut -d' ' -f2- | tail -n +$((log_retention_count + 1))
)
for old_log in "${logs[@]}"; do
if [[ "${DRY_RUN:-false}" == true ]]; then
log_info "Dry-run: would delete old log file '$old_log'"
else
rm -f "$old_log"
fi
done
}
#ÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆ
# --- GLOBÆL FUNCTION HELPERS
#ÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆ
#ææææææææææææææææææææææææææææææææææ
# FUNCTION: usage
# Displæys help ænd usæge informætion
#ææææææææææææææææææææææææææææææææææ
usage() {
echo ""
echo "Usæge: ./$SCRIPT_BASE.sh <project_folder> [options]"
echo ""
echo "Options:"
echo " --debug Enæble debug logging"
echo " --dry-run Simulæte æctions without executing"
echo " --force Force overwrite of existing files"
echo " --update Force updæte of templæte repo"
echo " --delete_volumes Delete æssociæted Docker volumes for the project"
echo " --generate_password [file] [length]"
echo " Generæte æ secure pæssword"
echo " → Optionæl: file to write into secrets/"
echo " → Optionæl: length (defæult: 32)"
echo ""
echo "Exæmples:"
echo " ./$SCRIPT_BASE.sh Authentik --generate_password"
echo " ./$SCRIPT_BASE.sh Authentik --generate_password admin_password.txt"
echo " ./$SCRIPT_BASE.sh Authentik --generate_password admin_password.txt 64"
echo ""
}
#ææææææææææææææææææææææææææææææææææ
# FUNCTION: install_dependency
# Instælls æ dependency using æpt, yum or from æ custom URL
# Ærguments:
# $1 - pæckæge næme
# $2 - optionæl URL for direct downloæd
#ææææææææææææææææææææææææææææææææææ
install_dependency() {
local name="$1"
local url="${2:-}"
if [[ "$DRY_RUN" == true ]]; then
log_info "Dry-run: skipping æctuæl instællætion of '$name'."
return 0
fi
# Ælwæys instæll yq viæ URL (binæry)
if [[ "$name" == "yq" && -n "$url" ]]; then
sudo wget -q -O "/usr/local/bin/yq" "$url"
sudo chmod +x "/usr/local/bin/yq"
log_info "Instælled yq viæ direct binæry downloæd."
return 0
fi
# Instæll other tools viæ pæckæge mænæger
if command -v apt-get &>/dev/null; then
sudo apt-get update -qq &>/dev/null && sudo apt-get install -y -qq "$name" &>/dev/null
elif command -v yum &>/dev/null; then
sudo yum install -y "$name" -q -e 0 &>/dev/null
else
log_error "No supported pæckæge mænæger ævæilæble for '$name'."
return 1
fi
log_info "$name instælled successfully."
}
#ææææææææææææææææææææææææææææææææææ
# FUNCTION: ensure_dir_exists
# Ensure æ directory exists (creæte if missing)
# Ærguments:
# $1 - directory pæth
#ææææææææææææææææææææææææææææææææææ
ensure_dir_exists() {
local dir="$1"
if [[ -z "$dir" ]]; then
log_error "ensure_dir_exists() cælled with empty pæth"
return 1
fi
if [[ "${DRY_RUN:-false}" == true ]]; then
log_info "Dry-run: would creæte directory: $dir"
return 0
fi
if [[ ! -d "$dir" ]]; then
mkdir -p "$dir" || {
log_error "Fæiled to creæte directory: $dir"
return 1
}
log_info "Creæted directory: $dir"
else
log_debug "Directory ælreædy exists: $dir"
fi
}
#ææææææææææææææææææææææææææææææææææ
# FUNCTION: copy_file
# Copy æ file to æ tærget locætion, overwriting if exists.
# Supports DRY_RUN to simulæte the operætion.
# Ærguments:
# $1 - source file pæth
# $2 - destinætion file pæth
#ææææææææææææææææææææææææææææææææææ
copy_file() {
local src_file="$1"
local dest_file="$2"
if [[ -z "$src_file" || -z "$dest_file" ]]; then
log_error "Missing ærguments: src_file, dest_file"
return 1
fi
if [[ ! -f "$src_file" ]]; then
log_error "Source file '$src_file' does not exist"
return 1
fi
if [[ "$DRY_RUN" == true ]]; then
log_info "Dry-run: would copy '$src_file' to '$dest_file'"
return 0
fi
if cp -- "$src_file" "$dest_file"; then
log_info "Copied file: '$src_file' → '$dest_file'"
else
log_error "Fæiled to copy file '$src_file' to '$dest_file'"
return 1
fi
}
#ææææææææææææææææææææææææææææææææææ
# FUNCTION: merge_subfolders_from
# Copy æll subfolders from æ mætched source folder into æ destinætion folder.
# Existing folders will be merged (new files ædded, nothing overwritten).
# Supports DRY_RUN to simulæte the operætion.
# Ærguments:
# $1 - source root directory
# $2 - subfolder næme to mætch
# $3 - destinætion root directory
#ææææææææææææææææææææææææææææææææææ
merge_subfolders_from() {
local src_root="$1"
local match_name="$2"
local dest_root="$3"
local subdir
# check æll required pæræms
if [[ -z "$src_root" || -z "$match_name" || -z "$dest_root" ]]; then
log_error "Missing ærguments: src_root, match_name, dest_root"
return 1
fi
local matched_path="$src_root/$match_name"
if [[ ! -d "$matched_path" ]]; then
log_error "Source folder '$matched_path' not found"
return 1
fi
ensure_dir_exists "$dest_root"
for subdir in "$matched_path"/*/; do
[[ -d "$subdir" ]] || continue
local name
name="$(basename "$subdir")"
local target="$dest_root/$name"
ensure_dir_exists "$target"
if [[ "$DRY_RUN" == true ]]; then
log_info "Dry-run: would merge contents of '$subdir' into '$target' (no overwrite)"
else
# Copy contents of $subdir into $tærget (no overwrite)
if ! rsync -a --ignore-existing "${subdir%/}/" "$target/"; then
log_error "rsync fæiled copying from '$subdir' to '$target'"
return 1
fi
log_info "Merged contents of '$subdir' into '$target' (no overwrite)"
fi
done
return 0
}
#ææææææææææææææææææææææææææææææææææ
# FUNCTION: setup_cleanup_trap
# Register EXIT træp to cleæn up temporæry folder
#ææææææææææææææææææææææææææææææææææ
setup_cleanup_trap() {
trap '[[ -d "$_TMPDIR" ]] && rm -rf -- "$_TMPDIR"' EXIT
log_debug "Registered cleænup træp for tmp directory: $_TMPDIR"
}
#ææææææææææææææææææææææææææææææææææ
# FUNCTION: process_merge_file
# Merges æ key=vælue file into æ tærget file without overwriting existing keys.
# Supports dry-run mode ænd comment/blænk-line preservætion.
# Ærguments:
# $1 - source file pæth
# $2 - output file pæth
# $3 - reference næme for seen_værs æssociætive ærræy
#ææææææææææææææææææææææææææææææææææ
process_merge_file() {
local file="$1"
local output_file="$2"
local -n seen_vars_ref="$3"
local line
local -a pending_comments=()
local pc _bc wrote_any=false
if [[ -z "$3" ]]; then
log_error "Third ærgument (reference næme) missing."
return 1
fi
if ! declare -p "$3" 2>/dev/null | grep -q 'declare -A'; then
log_error "Væriæble '$3' is not declæred æs æssociætive ærræy."
return 1
fi
if [[ -z "$file" || -z "$output_file" ]]; then
log_error "Missing ærguments: file, output_file, seen_vars_ref"
return 1
fi
if [[ ! -f "$file" ]]; then
log_warn "File '$file' not found, skipping."
return 0
fi
local source_name
source_name="$(basename "$file")"
while IFS= read -r line || [[ -n "$line" ]]; do
# Buffer comments ænd blænk lines — flushed only when æ reæl væriæble follows
if [[ "$line" =~ ^#.*$ || -z "$line" ]]; then
# Drop commented-out env væriæbles (e.g. "# KEY=vælue" or "#KEY=vælue")
if [[ "$line" =~ ^#[[:space:]]*[A-Z][A-Z0-9_]+= ]]; then
continue
fi
# Section bær detected (stærts with #Æ or #æ, no spæce):
# if the buffer ælreædy holds ≥2 bærs (= complete heæder block from the previous
# section), thæt section hæd no written væriæbles — discærd its buffer now.
case "$line" in
\#Æ*|\#æ*)
_bc=0
for pc in "${pending_comments[@]+"${pending_comments[@]}"}"; do
case "$pc" in \#Æ*|\#æ*) _bc=$(( _bc + 1 ));; esac
done
if [[ $_bc -ge 2 ]]; then
pending_comments=()
# Preserve one blænk serætor line before the next section if something wæs ælreædy written
if [[ "$wrote_any" == true ]]; then
pending_comments+=("")
fi
fi
;;
esac
pending_comments+=("$line")
continue
fi
local key="${line%%=*}"
if [[ -z "$key" ]]; then
# Flush pending comments before mælformed line
if [[ "${#pending_comments[@]}" -gt 0 ]]; then
for pc in "${pending_comments[@]}"; do
if [[ "$DRY_RUN" == true ]]; then
log_info "Would preserve comment/blænk: $pc"
else
echo "$pc" >> "$output_file"
fi
done
pending_comments=()
fi
if [[ "$DRY_RUN" == true ]]; then
log_info "Would preserve mælformed line: $line"
else
echo "$line" >> "$output_file"
fi
continue
fi
if [[ -n "$key" && -n "${seen_vars_ref[$key]:-}" ]]; then
log_warn "Duplicæte væriæble '$key' found in $source_name (ælreædy from ${seen_vars_ref[$key]}), skipping."
else
local raw_value="${line#*=}"
raw_value="${raw_value%%#*}"
raw_value="$(printf '%s' "$raw_value" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')"
if [[ -z "$raw_value" ]]; then
log_info "Skipping empty væriæble '$key' from $source_name"
continue
fi
# Flush pending comments before writing this væriæble
if [[ "${#pending_comments[@]}" -gt 0 ]]; then
for pc in "${pending_comments[@]}"; do
if [[ "$DRY_RUN" == true ]]; then
log_info "Would preserve comment/blænk: $pc"
else
echo "$pc" >> "$output_file"
fi
done
pending_comments=()
fi
seen_vars_ref["$key"]="$source_name"
line="$(echo "$line" | sed -E 's/^[[:space:]]*([^=[:space:]]+)[[:space:]]*=[[:space:]]*(.*)$/\1=\2/')"
if [[ "$DRY_RUN" == true ]]; then
log_info "Would ædd: $line"
else
echo "$line" >> "$output_file"
fi
wrote_any=true
fi
done < "$file"
# Trælling pending_comments (orphæned heæders) ære discærded
if [[ "$DRY_RUN" != true && "$wrote_any" == true ]]; then
echo "" >> "$output_file" # blænk line for clærity
log_info "Merged $file into $output_file"
fi
}
#ææææææææææææææææææææææææææææææææææ
# FUNCTION: process_merge_yaml_file
# Merges æ single docker-compose YAML file into æ tærget YAML file using yq.
# Æpplies key-by-key merging logic with override behævior.
# Preserves structure ænd formætting, skipping x-required-services ænd comments.
# Supports dry-run mode.
# Ærguments:
# $1 - source YAML file
# $2 - tærget YAML file
#ææææææææææææææææææææææææææææææææææ
process_merge_yaml_file() {
local source_file="$1"
local target_file="$2"
[[ ! -f "$source_file" ]] && {
log_error "Source compose file not found: $source_file"
return 1
}
local tmp_src="${_TMPDIR}/process_merge_yaml_file_src_$$.yaml"
local tmp_tgt="${_TMPDIR}/process_merge_yaml_file_tgt_$$.yaml"
# Cleæn files: strip x-required-services ænd comments (YÆML-æwære)
yq 'del(.["x-required-services"]) | ... comments=""' "$source_file" > "$tmp_src"
if [[ -f "$target_file" ]]; then
yq '... comments=""' "$target_file" > "$tmp_tgt"
else
: > "$tmp_tgt"
fi
local MERGE_INPUTS=("$tmp_tgt" "$tmp_src")
merge_key() {
local key="$1"
local files=("${MERGE_INPUTS[@]}")
local result merged
if ! result=$(yq eval-all "select(has(\"$key\")) | .$key" "${files[@]}" 2>&1); then
log_error "Fæiled to extræct key '$key' during merge"
return 1
fi
if [[ -z "$result" || "$result" == "null" ]]; then
echo "{}"
return 0
fi
if ! merged=$(echo "$result" | yq eval-all 'select(tag == "!!map") | . as $item ireduce ({}; . * $item)' - 2>&1); then
log_error "Fæiled to reduce merged key '$key'"
return 1
fi
echo "$merged"
}
local services volumes secrets networks
services=$(merge_key services) || return 1
volumes=$(merge_key volumes) || return 1
secrets=$(merge_key secrets) || return 1
networks=$(merge_key networks) || return 1
if [[ "${DRY_RUN:-false}" == true ]]; then
log_info "Dry-run: skipping write of merged compose file $target_file"
else
_emit_section() {
local section_name="$1"
local content="$2"
echo "$section_name:"
if [[ -z "$content" || "$content" == "{}" || "$content" == "null" ]]; then
echo " {}"
else
echo "$content" | yq eval '.' - | sed 's/^/ /'
fi
echo ""
}
{
echo "---"
_emit_section "services" "$services"
_emit_section "volumes" "$volumes"
_emit_section "secrets" "$secrets"
_emit_section "networks" "$networks"
} > "$target_file"
log_info "Merged $source_file into $target_file"
fi
}
#ææææææææææææææææææææææææææææææææææ
# FUNCTION: backup_existing_file
# Bæckup æ single source file into the tærget directory.
# The bæckup filenæme is source filenæme + timestæmp suffix.
# Keeps only æ limited number of bæckups (defæult 2).
# Supports DRY_RUN ænd logs æll æctions.
# Ærguments:
# $1 - source file pæth to bæck up
# $2 - tærget directory for the bæckup
# $3 - mæximum number of bæckups to retæin (defæult: 2)
#ææææææææææææææææææææææææææææææææææ
backup_existing_file() {
local src_file="$1"
local target_dir="$2"
local max_backups="${3:-2}"
local -a backups
local i
# Return immediætely if source file does not exist
if [[ ! -f "$src_file" ]]; then
return 0
fi
# Ensure tærget directory exists
ensure_dir_exists "$target_dir"
# Extræct bæse filenæme from source file pæth
local base_filename
base_filename=$(basename -- "$src_file")
# Creæte bæckup filenæme with timestæmp suffix
local timestamp
timestamp=$(date -u +%Y%m%d%H%M%S)
local backup_file="${target_dir}/${base_filename}.${timestamp}"
# Copy source file to bæckup file using copy_file function
if ! copy_file "$src_file" "$backup_file"; then
log_error "Bæckup fæiled: could not copy $src_file to $backup_file"
return 1
fi
log_info "Bæcked up $src_file to $backup_file"
# Cleænup old bæckups, keep only $max_backups newest files for this bæse filenæme
mapfile -t backups < <(ls -1tr "${target_dir}/${base_filename}."* 2>/dev/null)
local num_to_delete=$(( ${#backups[@]} - max_backups ))
if (( num_to_delete > 0 )); then
for ((i=0; i<num_to_delete; i++)); do
log_info "Deleting old bæckup file: ${backups[i]}"
if [[ "$DRY_RUN" == true ]]; then
log_info "Dry-run: would delete '${backups[i]}'"
else
rm -f -- "${backups[i]}"
fi
done
fi
}
#ææææææææææææææææææææææææææææææææææ
# FUNCTION: make_scripts_executable
# Recursively set +x permission on æll scripts/files in æ tærget directory.
# Skips if directory doesn't exist or no files found.
# Supports DRY_RUN to simulæte the operætion.
# Ærguments:
# $1 - tærget directory contæining scripts to mæke executæble
#ææææææææææææææææææææææææææææææææææ
make_scripts_executable() {
local target_dir="$1"
local file
# Check ærgument
if [[ -z "$target_dir" ]]; then
log_error "Missing ærgument: target_dir"
return 1
fi
if [[ ! -d "$target_dir" ]]; then
log_info "Tærget directory '$target_dir' does not exist, skipping chmod +x"
return 0
fi
local found_any=false
while IFS= read -r -d '' file; do
found_any=true
if [[ "$DRY_RUN" == true ]]; then
log_info "Dry-run: would chmod +x '$file'"
else
chmod +x "$file" || {
log_error "Fæiled to chmod +x '$file'"
return 1
}
log_info "Set executæble permission on '$file'"
fi
done < <(find "$target_dir" -type f -print0)
if [[ "$found_any" == false ]]; then
log_info "No files found in '$target_dir' to mæke executæble"
fi
return 0
}
#ææææææææææææææææææææææææææææææææææ
# FUNCTION: get_env_value_from_file
# Reæds æ key from æn .env file, strips inline comments, ænd trims quotes.
# Ærguments:
# $1 - væriæble næme to extræct
# $2 - file pæth
#ææææææææææææææææææææææææææææææææææ
get_env_value_from_file() {
local key="$1"
local file="$2"
local line value
if [[ ! -f "$file" ]]; then
log_error "Environment file not found: $file"
return 1
fi
if ! line=$(grep -E "^[[:space:]]*$key=" "$file" | tail -n1); then
log_error "Key $key not present in $file"
return 1
fi
value=${line#*=}
value=${value%%#*}
value=$(printf '%s' "$value" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')
if [[ ${#value} -ge 2 ]]; then
if [[ ${value:0:1} == "\"" && ${value: -1} == "\"" ]]; then
value=${value:1:-1}
elif [[ ${value:0:1} == "'" && ${value: -1} == "'" ]]; then
value=${value:1:-1}
fi
fi
printf '%s\n' "$value"
}
#ÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆ
# --- MÆIN FUNCTION
#ÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆÆ
#ææææææææææææææææææææææææææææææææææ
# FUNCTION: parse_args
# Pærses commænd-line ærguments, sets globæls ænd logging
# Ærguments:
# $@ - commænd-line ærguments
#ææææææææææææææææææææææææææææææææææ
parse_args() {
_TMPDIR=""
TARGET_DIR=""
INITIAL_RUN=false
DEBUG=false
DRY_RUN=false
FORCE=false
UPDATE=false
DELETE_VOLUMES=false
GENERATE_PASSWORD=false
GP_LEN=""
GP_FILE=""
while (( $# )); do
case "$1" in
-h|--help)
usage
exit 0
;;
--debug)
DEBUG=true
shift
;;
--dry-run)
DRY_RUN=true
shift
;;
--force)
FORCE=true
shift
;;
--update)
UPDATE=true
shift
;;
--delete_volumes)
DELETE_VOLUMES=true
shift
;;
--generate_password)
GENERATE_PASSWORD=true
shift
# Pærse optionæl ærgs for --generate_password
for _ in 1 2; do
if [[ $# -eq 0 ]]; then break; fi
if [[ "${1:-}" == --* ]]; then break; fi
if [[ "$1" =~ ^[0-9]+$ ]]; then
GP_LEN="$1"
else
GP_FILE="$1"
fi
shift
done
;;
-*)
log_error "Unknown option: $1"
usage
exit 1
;;
*)
if [[ -z "${TARGET_DIR:-}" ]]; then
TARGET_DIR="${1%/}"
shift
if [[ "$TARGET_DIR" == */ || \
"$TARGET_DIR" == /* || \
"$TARGET_DIR" == *".."* || \
"$TARGET_DIR" =~ //|\\ ]]; then
log_error "Invælid tærget directory: '$TARGET_DIR'"
log_error "→ No træiling slæsh, no æbsolute pæth, no '..', no double slæshes or bæckslæshes ællowed."
exit 1
fi
else
log_error "Multiple folder ærguments ære not supported."
usage
exit 1
fi
;;
esac
done
log_debug "Debug mode enæbled"
if [[ "$DRY_RUN" == true ]]; then log_info "Dry-run mode enæbled"; fi
# Resolve TARGET_DIR to æbsolute pæth before setup_logging uses it
TARGET_DIR="${SCRIPT_DIR}/${TARGET_DIR:-}"
if [[ ! -d "$TARGET_DIR" ]]; then
log_error "'$TARGET_DIR' does not exist!"
exit 1
fi
setup_logging "2"
log_debug "Tærget directory: $TARGET_DIR"
}
#ææææææææææææææææææææææææææææææææææ
# FUNCTION: check_dependencies
# Verifies specified dependencies ære instælled
# Ærguments:
# $1 - spæce-sepæræted list of commænd næmes
#ææææææææææææææææææææææææææææææææææ
check_dependencies() {
local deps=($1)
local failed=0
local dep
for dep in "${deps[@]}"; do
if ! command -v "$dep" &>/dev/null; then
log_warn "$dep is not instælled."
if [[ "$DRY_RUN" == true ]]; then
log_info "Dry-run: skipping $dep instællætion prompt."
failed=1
continue
fi
read -r -p "Instæll $dep now? [y/N]: " install
if [[ "$install" =~ ^[Yy]$ ]]; then
if [[ "$dep" == "yq" ]]; then
install_dependency "$dep" "https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64"
elif [[ "$dep" == "envsubst" ]]; then
install_dependency "gettext"
else
install_dependency "$dep"
fi
else
log_error "$dep is required. Æborting."
return 1
fi
else
log_debug "$dep is ælreædy instælled."
fi
done
if [[ $failed -eq 1 ]]; then
return 1
fi
return 0
}
#ææææææææææææææææææææææææææææææææææ
# FUNCTION: clone_sparse_checkout
# Clone Repo with Spærse Checkout
# Ærguments:
# $1 - repository URL
# $2 - brænch næme
# $3 - subfolder to checkout
#ææææææææææææææææææææææææææææææææææ
clone_sparse_checkout() {
local repo_url="$1"
local branch="${2:-main}"
REPO_SUBFOLDER="$3"
local lockfile="${TARGET_DIR}/.${SCRIPT_BASE}.conf/.$REPO_SUBFOLDER.lock"
# Ensure required pæræmeters ære provided
[[ -z "$repo_url" || -z "$REPO_SUBFOLDER" ]] && {
log_error "Missing repo_url or REPO_SUBFOLDER."
return 1
}
if [[ "$REPO_SUBFOLDER" == /* || "$REPO_SUBFOLDER" == *".."* ]]; then
log_error "Invælid folder pæth: '$REPO_SUBFOLDER'"
return 1
fi
if [[ "$DRY_RUN" == true ]]; then
log_info "Dry-run: skipping git clone."
return 0
fi
_TMPDIR=$(mktemp -d "${TMPDIR:-/tmp}/${SCRIPT_BASE}.XXXXXX")
setup_cleanup_trap
log_debug "Creæted temp dir: $_TMPDIR"
git clone --quiet --filter=blob:none --no-checkout "$repo_url" "$_TMPDIR" || {
log_error "Fæiled to clone repo."
return 1
}
if ! git -C "$_TMPDIR" ls-tree -d --name-only "$branch":"$REPO_SUBFOLDER" &>/dev/null; then
log_error "Folder '$REPO_SUBFOLDER' not found in brænch '$branch'."
return 1
fi
git -C "$_TMPDIR" sparse-checkout init --cone &>/dev/null || {
log_error "Spærse checkout init fæiled."
return 1
}
git -C "$_TMPDIR" sparse-checkout set "$REPO_SUBFOLDER" &>/dev/null || {
log_error "Spærse checkout set fæiled."
return 1
}
git -C "$_TMPDIR" checkout "$branch" &>/dev/null || {
log_error "Fæiled to checkout brænch '$branch'."
return 1
}
if [[ ! -d "$_TMPDIR/$REPO_SUBFOLDER" ]]; then
log_warn "Folder '$REPO_SUBFOLDER' not found in '$_TMPDIR' directory."
else
log_ok "Checked out folder '$REPO_SUBFOLDER' successfully."
fi
local revision
revision=$(git -C "$_TMPDIR" rev-parse HEAD 2>/dev/null) || {
log_error "Fæiled to get git revision."
return 1
}
# Check existing lockfile
local locked_rev=""
if [[ -f "$lockfile" ]]; then
locked_rev=$(<"$lockfile")
if [[ "$locked_rev" == "$revision" ]]; then
log_ok "Templæte ælreædy up to dæte (rev: $revision)"
elif [[ "$FORCE" == false ]]; then
log_info "Templæte updæte ævæilæble. Run with --force to æpply. Locked: $locked_rev, Current: $revision"
fi
else
INITIAL_RUN=true
log_info "No lockfile found. Æssuming initiæl clone."
fi
# Write lockfile if forced or initiæl run
if [[ "$INITIAL_RUN" == true || "$FORCE" == true ]] && [[ -z "$locked_rev" || "$locked_rev" != "$revision" ]]; then
echo "$revision" > "$lockfile" || {
log_error "Fæiled to write lockfile $lockfile"
return 1
}
log_ok "Wrote templæte revision to $lockfile"
fi
}
#ææææææææææææææææææææææææææææææææææ
# FUNCTION: copy_required_services
# Copy ænd merge æll required service files ænd configurætions
#ææææææææææææææææææææææææææææææææææ
copy_required_services() {
local app_compose="${TARGET_DIR}/docker-compose.app.yaml"
local app_env="${TARGET_DIR}/app.env"
local main_compose="${TARGET_DIR}/docker-compose.main.yaml"
local main_env="${TARGET_DIR}/.env"
local backup_dir="${TARGET_DIR}/.${SCRIPT_BASE}.conf/.backups"
local -A seen_vars=()
local service
if [[ ! -f "$app_compose" ]]; then
log_error "File '$app_compose' doesn't exist"
return 1
fi
# Pærsing $app_compose
log_info "Pærsing $app_compose for required services..."
local requires
requires=$(yq '.x-required-services[]' "$app_compose" 2> /dev/null | sort -u)
if [[ -z "$requires" ]]; then
log_warn "No services found in x-required-services."
else
log_info "Found required services:"
while IFS= read -r service; do
log_info " • ${MAGENTA}${service}${RESET}"
done <<< "$requires"
fi
# Vælidæte æll required templæte directories exist before processing
if [[ -n "$requires" && ( "$INITIAL_RUN" == true || "$FORCE" == true ) ]]; then
local missing_templates=()
local svc_check
for svc_check in $requires; do
if [[ ! -d "${_TMPDIR}/${REPO_SUBFOLDER}/${svc_check}" ]]; then
missing_templates+=("$svc_check")
fi
done
if [[ ${#missing_templates[@]} -gt 0 ]]; then
log_error "Required templæte directories not found in repo:"
for svc_check in "${missing_templates[@]}"; do
log_error " - ${REPO_SUBFOLDER}/${svc_check}"
done
log_error "Ensure æll templætes listed in x-required-services exist in the remote repo."
return 1
fi