-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy pathmain.sh
More file actions
executable file
·1229 lines (1114 loc) · 39.7 KB
/
Copy pathmain.sh
File metadata and controls
executable file
·1229 lines (1114 loc) · 39.7 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
shopt -s extdebug
set +o posix
set -Eeuo pipefail
IFS=$'\n\t'
declare -rgx APPLICATION_NAME='DockSTARTer'
declare -rgx APPLICATION_COMMAND='ds'
declare -rgx APPLICATION_REPO='https://github.com/GhostWriters/DockSTARTer'
declare -rgx APPLICATION_LEGACY_BRANCH='master'
declare -rgx APPLICATION_DEFAULT_BRANCH='main'
declare -rgx APPLICATION_FOLDER_NAME_DEFAULT='.dockstarter'
declare -rgx TEMPLATES_NAME='DockSTARTer-Templates'
declare -rgx TEMPLATES_REPO='https://github.com/GhostWriters/DockSTARTer-Templates'
declare -rgx TEMPLATES_DEFAULT_BRANCH='main'
declare -rgx TEMPLATES_PARENT_FOLDER_NAME='templates'
declare -rgx TEMPLATES_REPO_FOLDER_NAME='DockSTARTer-Templates'
assert_nameref_is_string() {
local type_info
type_info=$(declare -p "${1}" 2> /dev/null) || return 0
[[ ! ${type_info} =~ ^declare\ -[a-zA-Z]*[aA] ]] || fatal "Variable '{{|Var|}}${1}{{[-]}}' is an array, expected a string"
}
assert_nameref_is_array() {
local type_info
type_info=$(declare -p "${1}" 2> /dev/null) || return 0
[[ ${type_info} =~ ^declare\ -[a-zA-Z]*a ]] || fatal "Variable '{{|Var|}}${1}{{[-]}}' is a string, expected an array"
}
# Version Functions
# https://stackoverflow.com/questions/4023830/how-to-compare-two-strings-in-dot-separated-version-format-in-bash#comment92693604_4024263
vergte() { printf '%s\n%s' "${2}" "${1}" | sort -C -V; }
vergt() { ! vergte "${2}" "${1}"; }
verlte() { printf '%s\n%s' "${1}" "${2}" | sort -C -V; }
verlt() { ! verlte "${2}" "${1}"; }
# Check for supported bash version
declare REQUIRED_BASH_VERSION="4"
if verlt "${BASH_VERSION}" "${REQUIRED_BASH_VERSION}"; then
echo "Unsupported bash version."
echo "${APPLICATION_NAME} requires at least bash version ${REQUIRED_BASH_VERSION}, installed version is ${BASH_VERSION}."
exit 1
fi
readonly -a ARGS=("$@")
# Github Token for CI
if [[ ${CI-} == true ]] && [[ ${TRAVIS_SECURE_ENV_VARS-} == true ]]; then
readonly GH_HEADER="Authorization: token ${GH_TOKEN}"
export GH_HEADER
fi
declare DS_COMMAND
DS_COMMAND=$(command -v "${APPLICATION_COMMAND}" || true)
# User/Group Information
readonly DETECTED_PUID=${SUDO_UID:-$UID}
export DETECTED_PUID
DETECTED_UNAME=$(id -un "${DETECTED_PUID}" 2> /dev/null || true)
readonly DETECTED_UNAME
export DETECTED_UNAME
DETECTED_PGID=$(id -g "${DETECTED_PUID}" 2> /dev/null || true)
readonly DETECTED_PGID
export DETECTED_PGID
DETECTED_UGROUP=$(id -gn "${DETECTED_PUID}" 2> /dev/null || true)
readonly DETECTED_UGROUP
export DETECTED_UGROUP
DETECTED_HOMEDIR=$(eval echo "~${DETECTED_UNAME}" 2> /dev/null || true)
readonly DETECTED_HOMEDIR
export DETECTED_HOMEDIR
# System Information
ARCH=$(uname -m)
if [[ ${ARCH} == arm64 ]]; then
ARCH="aarch64"
fi
readonly ARCH
export ARCH
declare -Ag C DC
# Script Information
# https://stackoverflow.com/questions/59895/get-the-source-directory-of-a-bash-script-from-within-the-script-itself/246128#246128
get_scriptname() {
# https://stackoverflow.com/questions/35006457/choosing-between-0-and-bash-source/35006505#35006505
local SOURCE=${BASH_SOURCE[0]:-$0}
while [[ -L ${SOURCE} ]]; do # resolve ${SOURCE} until the file is no longer a symlink
local DIR
DIR=$(cd -P "$(dirname "${SOURCE}")" > /dev/null 2>&1 && pwd)
SOURCE=$(readlink "${SOURCE}")
[[ ${SOURCE} != /* ]] && SOURCE="${DIR}/${SOURCE}" # if ${SOURCE} was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
echo "${SOURCE}"
}
SCRIPTPATH=$(cd -P "$(dirname "$(get_scriptname)")" > /dev/null 2>&1 && pwd)
readonly SCRIPTPATH
export SCRIPTPATH
SCRIPTNAME="${SCRIPTPATH}/$(basename "$(get_scriptname)")"
readonly SCRIPTNAME
export SCRIPTNAME
[[ -z ${XDG_DATA_HOME-} ]] && declare -gx XDG_DATA_HOME="${DETECTED_HOMEDIR}/.local/share"
[[ -z ${XDG_CONFIG_HOME-} ]] && declare -gx XDG_CONFIG_HOME="${DETECTED_HOMEDIR}/.config"
[[ -z ${XDG_CACHE_HOME-} ]] && declare -gx XDG_CACHE_HOME="${DETECTED_HOMEDIR}/.cache"
[[ -z ${XDG_STATE_HOME-} ]] && declare -gx XDG_STATE_HOME="${DETECTED_HOMEDIR}/.local/state"
#[[ -z ${XDG_RUNTIME_DIR-} ]] && declare -gx XDG_RUNTIME_DIR="/run/user/${DETECTED_PUID}"
for XDG_FOLDER in "${XDG_DATA_HOME}" "${XDG_CONFIG_HOME}" "${XDG_CONFIG_HOME}/${APPLICATION_NAME,,}" "${XDG_CACHE_HOME}" "${XDG_STATE_HOME}" "${XDG_STATE_HOME}/${APPLICATION_NAME,,}"; do
if [[ ! -d ${XDG_FOLDER} ]]; then
if [[ -f ${XDG_FOLDER} ]]; then
# XDG_FOLDER exists, but it's not a folder, so remove it
sudo rm -f "${XDG_FOLDER}"
fi
mkdir -p "${XDG_FOLDER}"
sudo chown "${DETECTED_PUID}":"${DETECTED_PGID}" "${XDG_FOLDER}"
sudo chmod 700 "${XDG_FOLDER}"
fi
done
declare -rgx APPLICATION_LOG="${XDG_CONFIG_HOME}/${APPLICATION_NAME,,}/${APPLICATION_NAME,,}.log"
declare -rgx FATAL_LOG="${XDG_CONFIG_HOME}/${APPLICATION_NAME,,}/${APPLICATION_NAME,,}.fatal.log"
declare -rgx APPLICATION_UPDATE_RECORD="${XDG_STATE_HOME}/${APPLICATION_NAME,,}/${APPLICATION_NAME,,}.updated"
declare -Agx ColorCodes=(
[black]=K [red]=R [green]=G [yellow]=Y
[blue]=B [magenta]=M [cyan]=C [white]=W
)
resolve_styles() {
local _rs_val_
resolve_styles_into _rs_val_ "$@"
printf '%s\n' "${_rs_val_}"
}
resolve_styles_into() {
local -n _rsi_out_="${1}"
assert_nameref_is_string "${1}"
local style_map_name="${2}"
local -n style_map="${2}"
local val="${3}"
local last_val=""
local -i MaxResolves=100
local sem_p="${4-}" sem_s="${5-}"
local dir_p="${6-}" dir_s="${7-}"
while [[ ${MaxResolves} -gt 0 ]]; do
local regex p_tag content s_tag full_match
if [[ -n ${sem_p-} ]]; then
# Custom syntax
local esc_sem_p="${sem_p//\[/\\\[}"
esc_sem_p="${esc_sem_p//\|/\\|}"
esc_sem_p="${esc_sem_p//\{/\\\{}"
local esc_sem_s="${sem_s//\]/\\\]}"
esc_sem_s="${esc_sem_s//\|/\\|}"
esc_sem_s="${esc_sem_s//\}/\\\}}"
local esc_dir_p="${dir_p//\[/\\\[}"
esc_dir_p="${esc_dir_p//\|/\\|}"
esc_dir_p="${esc_dir_p//\{/\\\{}"
local esc_dir_s="${dir_s//\]/\\\]}"
esc_dir_s="${esc_dir_s//\|/\\|}"
esc_dir_s="${esc_dir_s//\}/\\\}}"
regex="(${esc_sem_p}|${esc_dir_p})([^]|}]*)(${esc_sem_s}|${esc_dir_s})"
[[ ${val} =~ ${regex} ]] || break
full_match="${BASH_REMATCH[0]}"
p_tag="${BASH_REMATCH[1]}"
content="${BASH_REMATCH[2]}"
s_tag="${BASH_REMATCH[3]}"
# Ensure matching prefix/suffix types
if [[ ${p_tag} == "${sem_p}" && ${s_tag} == "${sem_s}" ]]; then
if [[ ${content} == *":"* ]]; then
local base="${content%%:*}"
local mod="${content#*:}"
val="${val//"${full_match}"/"${sem_p}${base}${sem_s}${dir_p}${mod}${dir_s}"}"
continue
fi
elif [[ ${p_tag} != "${dir_p}" || ${s_tag} != "${dir_s}" ]]; then
# Mismatched tags
break
fi
else
# Default syntax: {{|...|}} or {{[...]}}
regex='\{\{(\[|\|)([^]|}]*)(\]|\|)\}\}'
[[ ${val} =~ ${regex} ]] || break
full_match="${BASH_REMATCH[0]}"
local type="${BASH_REMATCH[1]}"
content="${BASH_REMATCH[2]}"
local end_type="${BASH_REMATCH[3]}"
# Ensure matching start/end types (| with | and [ with ])
if [[ ${type} == "|" && ${end_type} == "|" ]]; then
p_tag="${type}"
s_tag="${end_type}"
if [[ ${content} == *":"* ]]; then
local base="${content%%:*}"
local mod="${content#*:}"
val="${val//"${full_match}"/"{{|${base}|}}{{[${mod}]}}"}"
continue
fi
elif [[ ${type} == "[" && ${end_type} == "]" ]]; then
p_tag="${type}"
s_tag="${end_type}"
else
break
fi
fi
[[ ${val} == "${last_val}" ]] && break
MaxResolves=$((MaxResolves - 1))
last_val="${val}"
local replacement=""
if [[ ${p_tag} == "|" || ${p_tag} == "${sem_p-}" ]]; then
# Semantic tag: lookup in map (Raw key)
if [[ -v style_map["${content}"] ]]; then
replacement="${style_map["${content}"]}"
fi
elif [[ ${p_tag} == "[" || ${p_tag} == "${dir_p-}" ]]; then
# Direct tag: Dynamic parsing for {{[...]}} or custom direct tags
local fg="" bg="" flags="" resolved=""
if [[ ${content} == "-" ]]; then
# Reset tag
if [[ ${style_map_name} == "DC" ]]; then
resolved='\Zn'
else
resolved="${S["-"]}"
fi
else
# Parse [fg:bg:flags]
if [[ ${content} == *":"* ]]; then
fg="${content%%:*}"
local rest="${content#*:}"
if [[ ${rest} == *":"* ]]; then
bg="${rest%%:*}"
flags="${rest#*:}"
else
bg="${rest}"
flags=""
fi
else
# Single part tag: is it a color name or a code or a flag?
local content_lower="${content,,}"
local content_upper="${content^^}"
if [[ -v ColorCodes[${content_lower}] ]]; then
fg="${content_lower}"
elif [[ -v F[${content_upper}] ]]; then
fg="${content_upper}"
else
flags="${content}"
fi
fi
# Resolve FG, BG, Flags
local -A ZC=([K]=0 [R]=1 [G]=2 [Y]=3 [B]=4 [M]=5 [C]=6 [W]=7)
if [[ -n ${fg} ]]; then
local fg_code="${ColorCodes[${fg,,}]-${fg^^}}"
if [[ ${style_map_name} == "DC" ]]; then
resolved+="\Z${ZC[${fg_code}]-0}"
elif [[ -v F[${fg_code}] ]]; then
resolved+="${F[${fg_code}]}"
fi
fi
if [[ -n ${bg} ]]; then
local bg_code="${ColorCodes[${bg,,}]-${bg^^}}"
if [[ ${style_map_name} == "DC" ]]; then
resolved+="\z${ZC[${bg_code}]-0}"
elif [[ -v B[${bg_code}] ]]; then
resolved+="${B[${bg_code}]}"
fi
fi
if [[ -n ${flags} ]]; then
local -i k
for ((k = 0; k < ${#flags}; k++)); do
local char="${flags:k:1}"
if [[ ${style_map_name} == "DC" ]]; then
case ${char} in
B) resolved+='\Zb' ;;
D) resolved+='\Zd' ;;
L) resolved+='\Zl' ;;
R) resolved+='\Zr' ;;
U) resolved+='\Zu' ;;
esac
elif [[ -v S[${char}] ]]; then
resolved+="${S[${char}]}"
fi
done
fi
fi
replacement="${resolved}"
fi
val="${val//"${full_match}"/"${replacement}"}"
done
_rsi_out_="${val}"
}
resolve_strings() {
local array_name="$1"
shift
local _rs_line_ _rs_out_
_resolve_strings_line_() {
if [[ -t 1 ]]; then
resolve_styles_into _rs_out_ "${array_name}" "${_rs_line_}"
else
strip_styles_into _rs_out_ "${_rs_line_}"
fi
printf '%s\n' "${_rs_out_}"
}
# Process every argument (and every line within those arguments), or read from STDIN if no arguments
if [[ $# -gt 0 ]]; then
local arg
for arg in "$@"; do
while IFS= read -r _rs_line_; do
_resolve_strings_line_
done <<< "${arg}"
done
else
while IFS= read -r _rs_line_ || [[ -n ${_rs_line_} ]]; do
_resolve_strings_line_
done
fi
}
strip_styles() {
local _ss_val_
strip_styles_into _ss_val_ "${1:-}"
printf '%s\n' "${_ss_val_}"
}
strip_styles_into() {
local -n _ssi_out_="${1}"
assert_nameref_is_string "${1}"
local _ssi_val_="${2:-}"
local _ssi_extglob_=0
shopt -q extglob || _ssi_extglob_=$?
shopt -s extglob
local _ssi_line_ _ssi_result_=""
while IFS= read -r _ssi_line_; do
_ssi_line_="${_ssi_line_//\{\{\|*([!|])|\}\}/}"
_ssi_line_="${_ssi_line_//\{\{\[*([!\]])\]\}\}/}"
_ssi_result_+="${_ssi_line_}"$'\n'
done <<< "${_ssi_val_}"
_ssi_result_="${_ssi_result_%$'\n'}"
[[ ${_ssi_extglob_} -ne 0 ]] && shopt -u extglob || true
_ssi_out_="${_ssi_result_}"
}
# shellcheck disable=SC2120
strip_strings() {
# Process every argument (and every line within those arguments), or read from STDIN if no arguments
if [[ $# -gt 0 ]]; then
printf '%s\n' "$@"
else
cat
fi | while IFS= read -r line || [[ -n ${line} ]]; do
# Call the single-string stripper for each line
strip_styles "$line"
done
}
# Terminal Colors
declare -Agr B=( # Background
[B]=$(tput setab 4 2> /dev/null || echo -e "\e[44m") # Blue
[C]=$(tput setab 6 2> /dev/null || echo -e "\e[46m") # Cyan
[G]=$(tput setab 2 2> /dev/null || echo -e "\e[42m") # Green
[K]=$(tput setab 0 2> /dev/null || echo -e "\e[40m") # Black
[M]=$(tput setab 5 2> /dev/null || echo -e "\e[45m") # Magenta
[R]=$(tput setab 1 2> /dev/null || echo -e "\e[41m") # Red
[W]=$(tput setab 7 2> /dev/null || echo -e "\e[47m") # White
[Y]=$(tput setab 3 2> /dev/null || echo -e "\e[43m") # Yellow
["-"]=$(tput setab 9 2> /dev/null || echo -e "\e[49m") # Default
)
declare -Agr F=( # Foreground
[B]=$(tput setaf 4 2> /dev/null || echo -e "\e[34m") # Blue
[C]=$(tput setaf 6 2> /dev/null || echo -e "\e[36m") # Cyan
[G]=$(tput setaf 2 2> /dev/null || echo -e "\e[32m") # Green
[K]=$(tput setaf 0 2> /dev/null || echo -e "\e[30m") # Black
[M]=$(tput setaf 5 2> /dev/null || echo -e "\e[35m") # Magenta
[R]=$(tput setaf 1 2> /dev/null || echo -e "\e[31m") # Red
[W]=$(tput setaf 7 2> /dev/null || echo -e "\e[37m") # White
[Y]=$(tput setaf 3 2> /dev/null || echo -e "\e[33m") # Yellow
["-"]=$(tput setaf 9 2> /dev/null || echo -e "\e[39m") # Default
)
declare -Agr S=(
[BS]=$(tput cup 1000 0 2> /dev/null || true) # Bottom of screen
["-"]=$(tput sgr0 2> /dev/null || echo -e "\e[0m") # No Color
[D]=$(tput dim 2> /dev/null || echo -e "\e[2m") # Dim
[d]=$(tput sgr0 2> /dev/null || echo -e "\e[0m") # No Dim
[L]=$(tput blink 2> /dev/null || echo -e "\e[5m") # Blink
[l]=$(tput sgr0 2> /dev/null || echo -e "\e[0m") # No Blink
[B]=$(tput bold 2> /dev/null || echo -e "\e[1m") # Bold
[b]=$(tput sgr0 2> /dev/null || echo -e "\e[0m") # No Bold
[U]=$(tput smul 2> /dev/null || echo -e "\e[4m") # Underline
[u]=$(tput rmul 2> /dev/null || echo -e "\e[24m") # No Underline
[R]=$(tput rev 2> /dev/null || echo -e "\e[7m") # Reverse Video
[r]=$(tput sgr0 2> /dev/null || echo -e "\e[0m") # No Reverse Video
)
DM="${S[D]}"
readonly DM
export DM
BL="${S[L]}"
readonly BL
export BL
BD="${S[B]}"
readonly BD
export BD
UL="${S[U]}"
readonly UL
export UL
NC="${S["-"]}"
readonly NC
export NC
BS="${S[BS]}"
readonly BS
export BS
declare -Ag C=( # Pre-defined colors
[Timestamp]="{{[::D]}}"
[Trace]="{{[blue]}}"
[Debug]="{{[blue]}}"
[Info]="{{[blue]}}"
[Notice]="{{[green]}}"
[Warn]="{{[yellow]}}"
[Error]="{{[red]}}"
[Fatal]="{{[white]}}{{[:red]}}"
[FatalFooter]="{{[-]}}"
[TraceHeader]="{{[red]}}"
[TraceFooter]="{{[red]}}"
[TraceFrameNumber]="{{[red]}}"
[TraceFrameLines]="{{[red]}}"
[TraceSourceFile]="{{[cyan]}}{{[::B]}}"
[TraceLineNumber]="{{[yellow]}}{{[::B]}}"
[TraceFunction]="{{[green]}}{{[::B]}}"
[TraceCmd]="{{[green]}}{{[::B]}}"
[TraceCmdArgs]="{{[green]}}"
[UnitTestPass]="{{[green]}}"
[UnitTestFail]="{{[red]}}"
[UnitTestFailArrow]="{{[red]}}"
[App]="{{[cyan]}}"
[ApplicationName]="{{[cyan]}}{{[::B]}}"
[Branch]="{{[cyan]}}"
[FailingCommand]="{{[red]}}"
[File]="{{[cyan]}}{{[::B]}}"
[Folder]="{{[cyan]}}{{[::B]}}"
[Program]="{{[cyan]}}"
[RunningCommand]="{{[green]}}{{[::B]}}"
[Theme]="{{[cyan]}}"
[Update]="{{[green]}}"
[User]="{{[cyan]}}"
[URL]="{{[cyan]}}{{[::U]}}"
[UserCommand]="{{[yellow]}}{{[::B]}}"
[UserCommandError]="{{[red]}}{{[::U]}}"
[UserCommandErrorMarker]="{{[red]}}"
[Var]="{{[magenta]}}"
[Version]="{{[cyan]}}"
[Yes]="{{[green]}}"
[No]="{{[red]}}"
[ButtonName]="{{[cyan]}}"
[UsageCommand]="{{[yellow]}}{{[::B]}}"
[UsageOption]="{{[yellow]}}"
[UsageApp]="{{[cyan]}}"
[UsageBranch]="{{[cyan]}}"
[UsageFile]="{{[cyan]}}{{[::B]}}"
[UsagePage]="{{[cyan]}}{{[::B]}}"
[UsageTheme]="{{[cyan]}}"
[UsageVar]="{{[magenta]}}"
)
for Style in "${!C[@]}"; do
resolve_styles_into C["$Style"] C "${C["$Style"]}"
done
# C must not be readonly so that dynamic styles can be cached!
indent_text() {
local -i IndentSize=${1}
shift
local IndentString
printf -v IndentString "%*s" "${IndentSize}" ""
local line
while IFS= read -r line; do
printf '%s%s\n' "${IndentString}" "${line}"
done <<< "$(printf '%s\n' "$@")"
}
indent_string_pipe() {
local -i IndentSize=${1}
indent_text ${IndentSize} "$(cat -)"
}
get_system_info() {
local -a Output=()
Output+=(
"{{|ApplicationName|}}${APPLICATION_NAME-}{{[-]}} [{{|Version|}}${APPLICATION_VERSION-}{{[-]}}]"
"{{|ApplicationName|}}${TEMPLATES_NAME-}{{[-]}} [{{|Version|}}${TEMPLATES_VERSION-}{{[-]}}]"
""
"Currently running as: $0 (PID $$)"
"Shell name from /proc/$$/exe: $(readlink /proc/$$/exe)"
""
"ARCH: ${ARCH-}"
"SCRIPTPATH: ${SCRIPTPATH-}"
"SCRIPTNAME: ${SCRIPTNAME-}"
"COMPOSE_FOLDER: ${COMPOSE_FOLDER-}"
"CONFIG_FOLDER: ${CONFIG_FOLDER-}"
""
"APPLICATION_INI_FILE: ${APPLICATION_INI_FILE-}"
"DETECTED_PUID: ${DETECTED_PUID-}"
"DETECTED_UNAME: ${DETECTED_UNAME-}"
"DETECTED_PGID: ${DETECTED_PGID-}"
"DETECTED_UGROUP: ${DETECTED_UGROUP-}"
"DETECTED_HOMEDIR: ${DETECTED_HOMEDIR-}"
)
# shellcheck disable=SC2016 # Expressions don't expand in single quotes, use double quotes for that.
Output+=(
""
'{{|RunningCommand|}}echo ${BASH_VERSION}{{[-]}}:'
"${BASH_VERSION-}"
)
[[ -f /etc/os-release ]] &&
Output+=(
""
"{{|RunningCommand|}}cat /etc/os-release{{[-]}}:"
"$(PrefixFileLines ' ' /etc/os-release)"
)
printf '%s\n' "${Output[@]}"
}
# Log Functions
MKTEMP_LOG=$(mktemp -t "${APPLICATION_NAME,,}.log.XXXXXXXXXX") || resolve_strings C "Failed to create temporary log file." "Failing command: {{|FailingCommand|}}mktemp -t \"${APPLICATION_NAME,,}.log.XXXXXXXXXX\""
readonly MKTEMP_LOG
echo "${APPLICATION_NAME} Log" > "${MKTEMP_LOG}"
flush_logs() {
if [[ -e ${APPLICATION_LOG} ]]; then
sudo chown "${DETECTED_PUID}:${DETECTED_PGID}" "${APPLICATION_LOG}" || true
fi
touch "${APPLICATION_LOG}"
cat "${MKTEMP_LOG:-/dev/null}" >> "${APPLICATION_LOG}" || true
tail -n 1000 "${APPLICATION_LOG}" > "${MKTEMP_LOG}" || true
cat "${MKTEMP_LOG}" > "${APPLICATION_LOG}" || true
rm -f "${MKTEMP_LOG}" &> /dev/null || true
}
log() {
local LogToTerminal=${1-}
local Message=${2-}
local StrippedMessage
strip_styles_into StrippedMessage "${Message-}"
if [[ ${LogToTerminal} == true ]]; then
if [[ -t 2 ]]; then
# Stderr is a TTY, output with color
resolve_strings C "${Message}" >&2
else
# Stderr is being redirected, output without color
printf '%s\n' "${StrippedMessage}" >&2
fi
fi
# Output the message to the log file without color
printf '%s\n' "${StrippedMessage}" >> "${MKTEMP_LOG}" || true
}
timestamped_log_into() {
local -n _tli_out_="${1}"
assert_nameref_is_string "${1}"
local _tli_LogLevelTag_="${2-}"
shift 2
local _tli_LogMessage_
printf -v _tli_LogMessage_ '%b\n' "$@"
_tli_LogMessage_="${_tli_LogMessage_%$'\n'}"
local _tli_Timestamp_
printf -v _tli_Timestamp_ '%(%F %T)T' -1
local _tli_result_="" _tli_line_ _tli_formatted_line_
while IFS= read -r _tli_line_; do
printf -v _tli_formatted_line_ "{{[-]}}{{|Timestamp|}}${_tli_Timestamp_}{{[-]}} ${_tli_LogLevelTag_} %s{{[-]}}\n" "${_tli_line_}"
_tli_result_+="${_tli_formatted_line_}"
done <<< "${_tli_LogMessage_}"
_tli_out_="${_tli_result_%$'\n'}"
}
timestamped_log() {
local _tl_result_
timestamped_log_into _tl_result_ "$@"
printf '%s\n' "${_tl_result_}"
}
trace() {
local _msg_
timestamped_log_into _msg_ "{{|Trace|}}[TRACE ]{{[-]}}" "$@"
log "${TRACE-}" "${_msg_}"
}
debug() {
local _msg_
timestamped_log_into _msg_ "{{|Debug|}}[DEBUG ]{{[-]}}" "$@"
log "${DEBUG-}" "${_msg_}"
}
info() {
local _msg_
timestamped_log_into _msg_ "{{|Info|}}[INFO ]{{[-]}}" "$@"
log "${VERBOSE-}" "${_msg_}"
}
notice() {
local _msg_
timestamped_log_into _msg_ "{{|Notice|}}[NOTICE]{{[-]}}" "$@"
log true "${_msg_}"
}
warn() {
local _msg_
timestamped_log_into _msg_ "{{|Warn|}}[WARN ]{{[-]}}" "$@"
log true "${_msg_}"
}
error() {
local _msg_
timestamped_log_into _msg_ "{{|Error|}}[ERROR ]{{[-]}}" "$@"
log true "${_msg_}"
}
fatal_notrace() {
local LogMessage
timestamped_log_into LogMessage "{{|Fatal|}}[FATAL ]{{[-]}}" "$@"
log true "${LogMessage}"
strip_styles_into LogMessage "${LogMessage-}"
printf '%s\n' "${LogMessage}" > "${FATAL_LOG}" || true
exit 1
}
fatal() {
local -i thisFuncLine=$((LINENO - 1))
local -a Stack=()
readarray -t Stack < <(get_system_info)
Stack+=("")
local -i StackSize=${#FUNCNAME[@]}
local -i FrameNumberLength=${#StackSize}
local NoFile="<nofile>"
local NoFunction="<nofunction>"
# Pre-calculate Arg Offsets for LIFO BASH_ARGV (with extdebug)
local -a ArgOffsets=()
local -i Offset=0
local -i j
for ((j = 0; j < StackSize; j++)); do
ArgOffsets[j]=${Offset}
Offset+=${BASH_ARGC[j]-0}
done
local indent=""
local -i i
for ((i = StackSize - 1; i >= 0; i--)); do
local func="${FUNCNAME[i]:-$NoFunction}"
local SourceFile="${BASH_SOURCE[i]:-$NoFile}"
local -i line="${thisFuncLine}"
if ((i > 0)); then
line="${BASH_LINENO[i - 1]:-0}"
fi
local prefix=""
local arrowIndent="${indent}"
if ((i < StackSize - 1)); then
prefix="{{|TraceFrameLines|}}└>{{[-]}}"
if [[ ${#indent} -ge 2 ]]; then
arrowIndent="${indent% }"
fi
fi
# Format: "Num: [Indent]Arrow File:Line (Function)"
local StackLineFormat="{{|TraceFrameNumber|}}%${FrameNumberLength}d{{[-]}}: ${arrowIndent}${prefix}{{|TraceSourceFile|}}%s{{[-]}}:{{|TraceLineNumber|}}%d{{[-]}} ({{|TraceFunction|}}%s{{[-]}})"
# shellcheck disable=SC2059 # Dynamic format string for padding
Stack+=(
"$(printf "${StackLineFormat}" "${i}" "${SourceFile##*/}" "${line}" "${func}")"
)
# Command and Arguments for this frame (Show what this frame CALLED)
if ((i > 0)); then
local next_i=$((i - 1))
local cmd="${FUNCNAME[next_i]:-$NoFunction}"
local -i CmdArgCount=${BASH_ARGC[next_i]-0}
local -i CurrentArg=${ArgOffsets[next_i]-0}
local FrameCmdPrefix="{{|TraceFrameLines|}}│{{[-]}}"
local FrameArgPrefix="{{|TraceFrameLines|}}│{{[-]}}"
local cmdString="{{|TraceCmd|}}${cmd}{{[-]}}"
local -a cmdArray=()
cmdArray+=("${FrameCmdPrefix}${cmdString}")
if [[ CmdArgCount -ne 0 ]]; then
for ((j = CurrentArg + CmdArgCount - 1; j >= CurrentArg; j--)); do
local cmdArgString="${BASH_ARGV[$j]}"
#cmdArgString="$(strip_styles "${cmdArgString}")"
cmdArgString="${cmdArgString//\\/\\\\}"
cmdArgString="{{[-]}}«{{|TraceCmdArgs|}}${cmdArgString}{{[-]}}»"
while read -r cmdLine; do
cmdArray+=(
"${FrameArgPrefix}{{|TraceCmdArgs|}}${cmdLine}"
)
done <<< "${cmdArgString}"
done
fi
# Align command block with the start of the frame text
local -i StackCmdIndent=$((FrameNumberLength + 2 + ${#indent}))
Stack+=(
"$(indent_text ${StackCmdIndent} "${cmdArray[@]}")"
)
fi
indent+=" "
done
fatal_notrace \
"{{|TraceHeader|}}### BEGIN SYSTEM INFORMATION AND STACK TRACE ###" \
"$(indent_text 2 "${Stack[@]}")" \
"{{|TraceFooter|}}### END SYSTEM INFORMATION AND STACK TRACE ###" \
"" \
"$@" \
"" \
"{{|FatalFooter|}}Please let the dev know of this error." \
"{{|FatalFooter|}}It has been written to '{{|File|}}${FATAL_LOG}{{|FatalFooter|}}'," \
"{{|FatalFooter|}}and appended to '{{|File|}}${APPLICATION_LOG}{{|FatalFooter|}}'."
}
PrefixFileLines() {
local Prefix="${1}"
local FileName="${2}"
local line
while IFS= read -r line || [[ -n ${line} ]]; do
printf '%s%s\n' "${Prefix}" "${line}"
done < "${FileName}"
}
RunAndLog() {
# RunAndLog [RunningNoticeType] [Prefix:[OutputNoticeType]] [ErrorNoticeType] [ErrorMessage] [Command]
# To skip an optional argument, pass an empty string
local -l RunningNoticeType=${1-}
local -l OutputNoticeType=${2-}
local -l ErrorNoticeType=${3-}
local ErrorMessage=${4-}
shift 4
local -a Command=("${@}")
local NoticeTypes_Regex='info|notice|warn|error|debug|trace'
local Prefix=''
if [[ ${OutputNoticeType} == *:* ]]; then
Prefix="${OutputNoticeType%%:*}:"
OutputNoticeType=${OutputNoticeType#"${Prefix}"}
Prefix="\t{{|RunningCommand|}}${Prefix}{{[-]}} "
fi
local OutputFile
local CommandText
CommandText="$(printf '%q ' "${Command[@]}" | xargs 2> /dev/null)"
# If the running notice type is set, log the command being run
[[ -n ${RunningNoticeType-} ]] &&
"${RunningNoticeType}" \
"Running: {{|RunningCommand|}}${CommandText}"
local ErrToNull=false
local OutToNull=false
if [[ ${OutputNoticeType-} =~ errtonull|bothtonull ]]; then
ErrToNull=true
fi
if [[ ${OutputNoticeType-} =~ outtonull|bothtonull ]]; then
OutToNull=true
fi
if [[ ${ErrToNull} != true || ${OutToNull} != true ]] && [[ ${OutputNoticeType-} =~ ${NoticeTypes_Regex} ]]; then
# If the output notice type is set, save the output to a file
OutputFile=$(mktemp -t "${APPLICATION_NAME}.${FUNCNAME[0]}.RunAndLogOutputFile.XXXXXXXXXX")
fi
local -i result=0
if [[ ${ErrToNull} == true && ${OutToNull} == true ]]; then
# Both stdout and stderr are redirected to /dev/null
"${Command[@]}" &> /dev/null || result=$?
elif [[ ${ErrToNull} == true && -n ${OutputFile-} ]]; then
# stderr redircted to /dev/null, stdout redirected to output file
"${Command[@]}" > "${OutputFile}" 2> /dev/null || result=$?
elif [[ ${OutToNull} == true && -n ${OutputFile-} ]]; then
# stdout redircted to /dev/null, stderr redirected to output file
"${Command[@]}" 2> "${OutputFile}" > /dev/null || result=$?
elif [[ -n ${OutputFile-} ]]; then
# Both stdout and stderr redirected to output file
"${Command[@]}" &> "${OutputFile}" || result=$?
else
# No redirection
"${Command[@]}" || result=$?
fi
if [[ -n ${OutputFile-} && -s ${OutputFile} ]]; then
local line
while IFS= read -r line || [[ -n ${line} ]]; do
"${OutputNoticeType}" "${Prefix}${line}"
done < "${OutputFile}"
rm -f "${OutputFile}"
fi
[[ ${result} -eq 0 ]] && return
if [[ -n ${ErrorNoticeType-} ]]; then
# If the error notice type is set, log the error
${ErrorNoticeType} \
"${ErrorMessage}" \
"Failing command: {{|FailingCommand|}}${CommandText}"
fi
return ${result}
}
[[ -f "${SCRIPTPATH}/includes/misc_functions.sh" ]] && source "${SCRIPTPATH}/includes/misc_functions.sh"
[[ -f "${SCRIPTPATH}/includes/global_variables.sh" ]] && source "${SCRIPTPATH}/includes/global_variables.sh"
[[ -f "${SCRIPTPATH}/includes/migration_functions.sh" ]] && source "${SCRIPTPATH}/includes/migration_functions.sh"
if declare -F MigrateFilesAndFolders > /dev/null; then
MigrateFilesAndFolders
fi
[[ -f "${SCRIPTPATH}/includes/pm_variables.sh" ]] && source "${SCRIPTPATH}/includes/pm_variables.sh"
[[ -f "${SCRIPTPATH}/includes/run_script.sh" ]] && source "${SCRIPTPATH}/includes/run_script.sh"
[[ -f "${SCRIPTPATH}/includes/tui_functions.sh" ]] && source "${SCRIPTPATH}/includes/tui_functions.sh"
[[ -f "${SCRIPTPATH}/includes/ds_functions.sh" ]] && source "${SCRIPTPATH}/includes/ds_functions.sh"
[[ -f "${SCRIPTPATH}/includes/test_functions.sh" ]] && source "${SCRIPTPATH}/includes/test_functions.sh"
[[ -f "${SCRIPTPATH}/includes/usage.sh" ]] && source "${SCRIPTPATH}/includes/usage.sh"
[[ -f "${SCRIPTPATH}/includes/cmdline.sh" ]] && source "${SCRIPTPATH}/includes/cmdline.sh"
# Check for supported CPU architecture
check_arch() {
if [[ ${ARCH} != "arm64" ]] && [[ ${ARCH} != "aarch64" ]] && [[ ${ARCH} != "x86_64" ]]; then
fatal_notrace \
"Unsupported architecture." \
"Supported architectures are 'aarch64' or 'x86_64', running architecture is '${ARCH}'."
fi
}
# Check if the repo exists relative to the SCRIPTPATH
check_repo() {
if RunAndLog info "git:info" "" "" git -C "${SCRIPTPATH}" rev-parse --is-inside-work-tree; then
if [[ -d ${SCRIPTPATH}/includes ]] && [[ -d ${SCRIPTPATH}/scripts ]]; then
return
else
return 1
fi
else
return 1
fi
}
# Check if the templates repo exists relative to the ${TEMPLATES_PARENT_FOLDER}
check_templates_repo() {
if RunAndLog info "git:info" "" "" git -C "${TEMPLATES_PARENT_FOLDER}" rev-parse --is-inside-work-tree; then
return
else
return 1
fi
}
# Check if running as root
check_root() {
if [[ ${DETECTED_PUID} == "0" ]] || [[ ${DETECTED_HOMEDIR} == "/root" ]]; then
fatal_notrace \
"Running as '{{|User|}}root{{[-]}}' is not supported." \
"Please run as a standard user."
fi
}
# Check if running with sudo
check_sudo() {
if [[ ${EUID} -eq 0 ]]; then
fatal_notrace \
"Running with '{{|UserCommand|}}sudo{{[-]}}' is not supported." \
"Commands requiring '{{|UserCommand|}}sudo{{[-]}}' will prompt automatically when required."
fi
}
clone_repo() {
local default_path="${DETECTED_HOMEDIR}/${APPLICATION_FOLDER_NAME_DEFAULT}"
local TargetPath=""
local symlink
symlink="$(command -v "${APPLICATION_COMMAND}" 2> /dev/null || true)"
if [[ -L ${symlink} ]]; then
local link_path
link_path=$(readlink -f "${symlink}")
if [[ $(basename "${link_path}") == "main.sh" ]]; then
TargetPath="$(dirname "${link_path}")"
warn "Existing {{|ApplicationName|}}${APPLICATION_NAME}{{[-]}} install found at '{{|Folder|}}${TargetPath}{{[-]}}', reinstalling to that location."
fi
fi
if [[ -z ${TargetPath} ]]; then
local Folder
for Folder in "${DETECTED_HOMEDIR}/.dockstarter" "${DETECTED_HOMEDIR}/.docker"; do
if [[ -d "${Folder}/compose" ]]; then
TargetPath="${Folder}"
warn "Existing compose folder found in '{{|Folder|}}${TargetPath}{{[-]}}', reinstalling to that location."
break
fi
done
fi
if [[ -z ${TargetPath} ]]; then
TargetPath="${default_path}"
fi
warn \
"Installing {{|ApplicationName|}}${APPLICATION_NAME}{{[-]}} to '{{|Folder|}}${TargetPath}{{[-]}}'." \
""
# Safely create and initialize the directory
RunAndLog notice "mkdir:notice" \
fatal "Failed to create {{|ApplicationName|}}${APPLICATION_NAME}{{[-]}} repo directory." \
mkdir -p "${TargetPath}"
RunAndLog notice "git:notice" \
fatal "Failed to initialize {{|ApplicationName|}}${APPLICATION_NAME}{{[-]}} repo." \
git -C "${TargetPath}" init -b "${APPLICATION_DEFAULT_BRANCH}"
# Handle the remote origin dynamically (avoids fatal error if already exists)
if ! RunAndLog notice "git:notice" warn "Failed to set origin, retrying with '{{|UserCommand|}}git remote add{{[-]}}'" git -C "${TargetPath}" remote set-url origin "${APPLICATION_REPO}"; then
RunAndLog notice "git:notice" fatal "Failed to add origin." git -C "${TargetPath}" remote add origin "${APPLICATION_REPO}"
fi
# Fetch specifically the target branch to save bandwidth
RunAndLog notice "git:notice" \
fatal "Failed to fetch {{|ApplicationName|}}${APPLICATION_NAME}{{[-]}} repo." \
git -C "${TargetPath}" fetch origin "${APPLICATION_DEFAULT_BRANCH}"
# Force overwrite all tracked files to match the remote branch
RunAndLog notice "git:notice" \
fatal "Failed to reset {{|ApplicationName|}}${APPLICATION_NAME}{{[-]}} repo." \
git -C "${TargetPath}" reset --hard "origin/${APPLICATION_DEFAULT_BRANCH}"
# Clean untracked files, skipping everything in .gitignore (like your compose folder)
RunAndLog notice "git:notice" \
fatal "Failed to clean {{|ApplicationName|}}${APPLICATION_NAME}{{[-]}} repo." \
git -C "$TargetPath" clean -df
# This bootstrap copy runs from outside the cloned repo, so
# includes/ds_functions.sh isn't sourced yet -- use plain git directly.
local ClonedVersion
ClonedVersion="$(git -C "${TargetPath}" describe --tags --exact-match 2> /dev/null || true)"
if [[ -z ${ClonedVersion} ]]; then
ClonedVersion="${APPLICATION_DEFAULT_BRANCH} commit $(git -C "${TargetPath}" rev-parse --short HEAD 2> /dev/null)"
fi
notice "Cloned {{|ApplicationName|}}${APPLICATION_NAME}{{[-]}} at '{{|Version|}}${ClonedVersion}{{[-]}}'."
local LatestTag
LatestTag="$(git -C "${TargetPath}" tag --merged "origin/${APPLICATION_DEFAULT_BRANCH}" --sort=-creatordate 2> /dev/null | head -1)" || true
if [[ -n ${LatestTag} ]]; then
local TagHash HeadHash
TagHash="$(git -C "${TargetPath}" rev-parse --quiet --verify "${LatestTag}^{commit}" 2> /dev/null)" || true
HeadHash="$(git -C "${TargetPath}" rev-parse --quiet --verify HEAD 2> /dev/null)" || true
if [[ -z ${TagHash} || ${TagHash} != "${HeadHash}" ]]; then
notice "Checking out {{|ApplicationName|}}${APPLICATION_NAME}{{[-]}} release '{{|Version|}}${LatestTag}{{[-]}}'"
RunAndLog info "git:info" \
fatal "Failed to switch to github ref '{{|Branch|}}${LatestTag}{{[-]}}'." \
git -C "${TargetPath}" checkout --force "${LatestTag}"
fi
fi
if [[ ${#ARGS[@]} -eq 0 ]]; then
notice \
"Performing first run install."
exec bash "${TargetPath}/main.sh" -yvi --config-show --version
else
exec bash "${TargetPath}/main.sh" "${ARGS[@]}"
fi
}
clone_templates_repo() {
warn \
"Attempting to clone {{|ApplicationName|}}${TEMPLATES_NAME}{{[-]}} repo to '{{|Folder|}}${TEMPLATES_PARENT_FOLDER}{{[-]}}' location."
if [[ -d ${TEMPLATES_PARENT_FOLDER?} ]]; then
RunAndLog notice "rm:notice" \
fatal "Failed to remove ${TEMPLATES_PARENT_FOLDER?}." \
sudo rm -rf "${TEMPLATES_PARENT_FOLDER?}"
fi
RunAndLog notice "git:notice" \
fatal "Failed to clone {{|ApplicationName|}}${TEMPLATES_NAME}{{[-]}} repo." \
git clone -b "${TEMPLATES_DEFAULT_BRANCH}" "${TEMPLATES_REPO}" "${TEMPLATES_PARENT_FOLDER}"
local ClonedVersion
templates_version_into ClonedVersion
notice "Cloned {{|ApplicationName|}}${TEMPLATES_NAME}{{[-]}} at '{{|Version|}}${ClonedVersion}{{[-]}}'."
templates_checkout_latest_release_after_clone
}
# Cleanup Function
cleanup() {
local -ri EXIT_CODE=$?
trap - ERR EXIT SIGABRT SIGALRM SIGHUP SIGINT SIGQUIT SIGTERM
flush_logs