-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocker_tool_suite.sh
More file actions
executable file
·3435 lines (2964 loc) · 143 KB
/
docker_tool_suite.sh
File metadata and controls
executable file
·3435 lines (2964 loc) · 143 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
# =========================
# --- Docker Tool Suite ---
# =========================
SCRIPT_VERSION=v1.5.4.8
# --- Strict Mode & Globals ---
set -euo pipefail
DRY_RUN=false
IS_CRON_RUN=false
# --- Cleanup Function ---
cleanup() {
local exit_code=$?
# Kill any background tail processes started by execute_and_log
if [[ -n "${tail_pid-}" ]]; then
kill "$tail_pid" 2>/dev/null || true
fi
# Remove any stray temp files if they exist
if [[ -n "${tmp_log-}" && -f "$tmp_log" ]]; then
rm -f "$tmp_log"
fi
# Ensure ownership of the log file if we are in sudo/cron mode
if [[ -n "${LOG_FILE-}" && -f "$LOG_FILE" && -n "${SUDO_USER-}" ]]; then
chown "${SUDO_USER}:${SUDO_USER}" "$LOG_FILE" 2>/dev/null || true
fi
exit "$exit_code"
}
trap cleanup EXIT SIGINT SIGTERM
# --- Initialize Terminal Cosmetics ---
if tput setaf 1 > /dev/null 2>&1; then
C_RED=$(tput setaf 1)
C_GREEN=$(tput setaf 2)
C_YELLOW=$(tput setaf 3)
C_CYAN=$(tput setaf 6)
T_BOLD=$(tput bold)
C_GRAY=$(tput bold)$(tput setaf 0)
C_RESET=$'\e[0m'
TICKMARK=$'\xE2\x9C\x93'
else
C_RED=""
C_GREEN=""
C_YELLOW=""
C_CYAN=""
T_BOLD=""
C_GRAY=""
C_RESET=""
TICKMARK="[OK]"
fi
# --- Standardized Footer Options ---
optionsRandQ=(
"${C_GRAY}(R)eturn to previous menu${C_RESET}"
"${C_RED}(Q)uit the tool${C_RESET}"
)
optionsOnlyQ=(
"${C_RED}(Q)uit the tool${C_RESET}"
)
# --- User & Path Detection ---
if [[ -n "${SUDO_USER-}" ]]; then
CURRENT_USER="${SUDO_USER}"
else
CURRENT_USER="${USER:-$(whoami)}"
fi
SCRIPT_PATH=$(readlink -f "$0")
# Capture original location before switching context
ORIGINAL_PWD="$PWD"
# Unconditionally switch to HOME or Root to prevent "getwd" errors
# if the original launch directory is deleted while the script is running.
cd "${HOME:-/}" 2>/dev/null || cd "/"
# --- Command Prefix for Sudo ---
SUDO_CMD=""
if [[ $EUID -ne 0 ]]; then
SUDO_CMD="sudo"
fi
# --- Config Loader ---
load_config() {
local cfg_file="$1"
tmp_log=$(mktemp)
if [[ ! -f "$cfg_file" ]]; then return 1; fi
# Filter using the new variable name
grep -E '^\s*(#|$)|^[A-Z_]+=".*"$|^[A-Z_]+='"'.*'"'$|^[A-Z_]+=[a-zA-Z0-9/+=._-]+$|^[A-Z_]+=\($|^\s*"[^"]+"$|^\)$' "$cfg_file" > "$tmp_log" || true
# Security check using the new variable name
if grep -qE '`|\$\(|;|\||&' "$tmp_log"; then
echo -e "${C_RED}SECURITY ERROR: Config file contains executable code indicators! Aborting.${C_RESET}"
rm -f "$tmp_log"
tmp_log=""
exit 1
fi
# Source and clean up
. "$tmp_log"
rm -f "$tmp_log"
tmp_log=""
}
validate_loaded_config() {
# Validate Retention (Integer, 0 to 3650)
if [[ ! "${LOG_RETENTION_DAYS}" =~ ^[0-9]+$ ]] || [ "${LOG_RETENTION_DAYS}" -gt 3650 ]; then
echo -e "${C_RED}Warning: Invalid LOG_RETENTION_DAYS detected ('${LOG_RETENTION_DAYS}').${C_RESET}"
echo -e "${C_YELLOW}-> Correction applied to config file (Reset to 30).${C_RESET}"
LOG_RETENTION_DAYS="30"
sed -i "/^LOG_RETENTION_DAYS=/c\LOG_RETENTION_DAYS=\"30\"" "$CONFIG_FILE"
fi
# Validate Compression Level (Integer, 0-9)
if [[ ! "${ARCHIVE_COMPRESSION_LEVEL}" =~ ^[0-9]+$ ]] || [ "${ARCHIVE_COMPRESSION_LEVEL}" -gt 9 ]; then
echo -e "${C_RED}Warning: Invalid ARCHIVE_COMPRESSION_LEVEL detected ('${ARCHIVE_COMPRESSION_LEVEL}').${C_RESET}"
echo -e "${C_YELLOW}-> Correction applied to config file (Reset to 3).${C_RESET}"
ARCHIVE_COMPRESSION_LEVEL="3"
sed -i "/^ARCHIVE_COMPRESSION_LEVEL=/c\ARCHIVE_COMPRESSION_LEVEL=\"3\"" "$CONFIG_FILE"
fi
# Validate Paths (Basic check to ensure they aren't empty)
if [[ -z "${APPS_BASE_PATH}" ]]; then APPS_BASE_PATH="/home/${CURRENT_USER}/apps"; fi
if [[ -z "${BACKUP_LOCATION}" ]]; then BACKUP_LOCATION="/home/${CURRENT_USER}/backups"; fi
}
# --- Unified Configuration Paths ---
CONFIG_DIR="/home/${CURRENT_USER}/.config/dtools"
CONFIG_FILE="${CONFIG_DIR}/config.conf"
# --- Helper: Pattern Matching ---
_is_item_ignored() {
local item="$1"
local -n ignore_list_ref="$2"
for pattern in "${ignore_list_ref[@]}"; do
# The right side is intentionally unquoted to allow bash globbing (wildcards)
if [[ "$item" == $pattern ]]; then
return 0
fi
done
return 1
}
# --- SHARED UI FUNCTION ---
print_standard_menu() {
local title="$1"
local -n _menu_options="$2"
local footer_mode="${3:-RQ}"
clear
echo "=============================================="
echo -e " ${C_GREEN}${T_BOLD}${title}${C_RESET}"
echo "=============================================="
echo -e " ${C_YELLOW}Options: "
for i in "${!_menu_options[@]}"; do
echo -e " ${C_CYAN}$((i+1))${C_YELLOW}) ${C_RESET}${_menu_options[$i]}"
done
echo -e "${C_RESET}----------------------------------------------"
if [[ "$footer_mode" == "RQ" ]]; then
for i in "${!optionsRandQ[@]}"; do echo -e " ${optionsRandQ[$i]}"; done
elif [[ "$footer_mode" == "Q" ]]; then
for i in "${!optionsOnlyQ[@]}"; do echo -e " ${optionsOnlyQ[$i]}"; done
fi
echo -e "${C_RESET}----------------------------------------------${C_RESET}"
}
# --- Encryption ---
KEY_FILE="${CONFIG_DIR}/.master.key"
get_secret_key() {
if [[ ! -d "$CONFIG_DIR" ]]; then
mkdir -p "$CONFIG_DIR"
chmod 700 "$CONFIG_DIR"
if [[ -n "${SUDO_USER-}" ]]; then chown "${SUDO_USER}:${SUDO_USER}" "$CONFIG_DIR"; fi
fi
if [[ ! -f "$KEY_FILE" ]]; then
openssl rand -base64 64 > "$KEY_FILE"
chmod 600 "$KEY_FILE"
if [[ -n "${SUDO_USER-}" ]]; then chown "${SUDO_USER}:${SUDO_USER}" "$KEY_FILE"; fi
fi
cat "$KEY_FILE"
}
encrypt_pass() {
local plaintext="$1"
printf '%s' "$plaintext" | openssl enc -aes-256-cbc -a -salt -pbkdf2 -iter 133337 -pass fd:3 3< <(get_secret_key) | tr -d '\n'
}
decrypt_pass() {
local encrypted_text="$1"
printf '%s\n' "$encrypted_text" | openssl enc -aes-256-cbc -a -d -salt -pbkdf2 -iter 133337 -pass fd:3 3< <(get_secret_key) 2>/dev/null || true
}
_record_image_state() {
local app_dir="$1"
local image_name="$2"
local image_id="$3"
local history_file="${app_dir}/.update_history"
if [[ "$image_id" == "not_found" || -z "$image_id" ]]; then return; fi
local entry
entry="$(date +'%Y-%m-%d %H:%M:%S')|${image_name}|${image_id}"
local last_entry
if [[ -f "$history_file" ]]; then
last_entry=$(tail -n 1 "$history_file")
if [[ "${last_entry#*|}" == "${image_name}|${image_id}" ]]; then
return
fi
fi
echo "$entry" >> "$history_file"
if [ "$(wc -l < "$history_file")" -gt 50 ]; then
local temp_hist; temp_hist=$(mktemp)
tail -n 50 "$history_file" > "$temp_hist"
mv "$temp_hist" "$history_file"
fi
}
_enable_cron_logging() {
local subdir="$1"
local prefix="$2"
local target_dir="${LOG_DIR}/${subdir}"
local current_date
current_date=$(date +'%Y-%m-%d')
local new_log_file="${target_dir}/${prefix}-${current_date}.log"
if [ ! -d "$target_dir" ]; then
mkdir -p "$target_dir"
if [[ -n "${SUDO_USER-}" ]]; then
chown "${SUDO_USER}:${SUDO_USER}" "$target_dir"
fi
fi
# Disable colors for cron logs
C_RED=""; C_GREEN=""; C_YELLOW=""; C_CYAN=""; T_BOLD=""; C_GRAY=""; C_RESET=""; TICKMARK="[OK]"
LOG_FILE="$new_log_file"
exec > >(while IFS= read -r line || [ -n "$line" ]; do echo "[$(date +'%Y-%m-%d %H:%M:%S')] $line"; done >> "$new_log_file") 2>&1
echo -e "Cron logging enabled. Output redirected to: $new_log_file"
}
check_root() {
if [[ $EUID -ne 0 ]]; then
echo -e "\n${C_YELLOW}This action requires root privileges. Please enter your password.${C_RESET}"
if ! sudo -v; then
echo -e "\n${C_RED}Authentication failed. Aborting.${C_RESET}" >&2
exit 1
fi
echo -e "\n${C_GREEN}Authentication successful.${C_RESET}\n"
fi
}
log() {
if [[ -n "${LOG_FILE-}" && "$IS_CRON_RUN" == "false" ]]; then echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"; fi
if [[ -n "${2-}" ]]; then echo -e "$2"; fi
}
execute_and_log() {
if $DRY_RUN; then
printf "${C_GRAY}[DRY RUN] Would execute: %q${C_RESET}\n" "$@"
return 0
fi
# Use the variable names recognized by the cleanup trap
tmp_log=$(mktemp)
tail_pid=""
# Only run tail if not in cron mode
if [[ "$IS_CRON_RUN" == "false" ]]; then
tail -f "$tmp_log" &> /dev/null &
tail_pid=$!
fi
"$@" &> "$tmp_log"
local exit_code=$?
# Stop tailing immediately after command finishes
if [[ -n "$tail_pid" ]]; then
kill "$tail_pid" 2>/dev/null || true
tail_pid=""
fi
if [[ "$IS_CRON_RUN" == "false" ]]; then
cat "$tmp_log" >> "${LOG_FILE:-/dev/null}"
fi
rm -f "$tmp_log"
tmp_log="" # Clear variable for trap safety
return "$exit_code"
}
check_deps() {
log "Checking dependencies..." "${C_GRAY}Checking dependencies...${C_RESET}"
local error_found=false
# Check binaries
if ! command -v docker &>/dev/null; then log "Error: Docker not found." "${C_RED}Error: Docker is not installed...${C_RESET}"; error_found=true; fi
if ! $SUDO_CMD docker compose version &>/dev/null; then log "Error: Docker Compose V2 not found." "${C_RED}Error: Docker Compose V2 not available...${C_RESET}"; error_found=true; fi
if ! command -v openssl &>/dev/null; then log "Error: openssl not found." "${C_RED}Error: 'openssl' is not installed (required for password encryption)...${C_RESET}"; error_found=true; fi
if ! command -v 7z &>/dev/null; then log "Warning: '7z' command not found." "${C_YELLOW}Warning: '7z' is not installed (required for secure archives)...${C_RESET}"; fi
# Check Daemon connectivity
if ! $SUDO_CMD docker info >/dev/null 2>&1; then
log "Error: Cannot connect to Docker Daemon."
echo -e "${C_RED}Error: Unable to connect to the Docker Daemon.${C_RESET}"
echo -e "${C_YELLOW}Please ensure the Docker service is running (e.g., 'sudo systemctl start docker') and the user has permissions.${C_RESET}"
error_found=true
fi
if $error_found; then exit 1; fi
log "Dependencies check passed." ""
}
find_compose_file() {
local app_dir="$1"
local compose_files=("compose.yaml" "compose.yml" "docker-compose.yaml" "docker-compose.yml")
for file in "${compose_files[@]}"; do if [ -f "$app_dir/$file" ]; then echo "$app_dir/$file"; return 0; fi; done
return 1
}
discover_apps() {
local path="$1"; local -n app_array="$2"
app_array=()
if [ ! -d "$path" ]; then echo "Warning: Directory not found for discovery: $path" >> "${LOG_FILE:-/dev/null}"; return; fi
shopt -s nullglob
local -a temp_list=()
for dir in "$path"/*/; do
if [ -d "$dir" ]; then
if find_compose_file "${dir%/}" &>/dev/null; then
temp_list+=("$(basename "$dir")")
fi
fi
done
shopt -u nullglob
# Use mapfile to sort the array safely, even with spaces
mapfile -t app_array < <(printf "%s\n" "${temp_list[@]}" | sort)
}
show_selection_menu() {
local title="$1" action_verb="$2"; local -n all_items_ref="$3"; local -n selected_status_ref="$4"
while true; do
clear
echo -e "====================================================="
echo -e " ${C_GREEN}${T_BOLD}${title}${C_RESET}"
echo -e "====================================================="
for i in "${!all_items_ref[@]}"; do
if ${selected_status_ref[$i]}; then echo -e " $((i+1)). ${C_GREEN}[x]${C_RESET} ${all_items_ref[$i]}"; else echo -e " $((i+1)). ${C_RED}[ ]${C_RESET} ${all_items_ref[$i]}"; fi
done
echo "-----------------------------------------------------"
echo -e "Enter a (${C_GREEN}No.${C_RESET}) to toggle, ${C_CYAN}(a)ll${C_RESET}, ${C_YELLOW}(${action_verb}) ${C_RESET}to ${C_YELLOW}${action_verb}${C_RESET}, ${C_GRAY}(r)eturn ${C_RESET}or ${C_RED}(q)uit${C_RESET}."
read -erp "Your choice: " choice
case "$choice" in
"${action_verb}")
local any_selected=false
for status in "${selected_status_ref[@]}"; do
if $status; then any_selected=true; break; fi
done
if ! $any_selected; then
echo -e "\n${C_YELLOW}No items selected. Try again.${C_RESET}"
sleep 2
continue
fi
return 0
;;
[rR]) return 1 ;;
[qQ]) exit 0 ;;
[aA])
local all_selected=true; for status in "${selected_status_ref[@]}"; do if ! $status; then all_selected=false; break; fi; done
local new_status; new_status=$(if $all_selected; then echo "false"; else echo "true"; fi)
for i in "${!selected_status_ref[@]}"; do selected_status_ref[i]=$new_status; done ;;
*)
if [[ "$choice" =~ ^[0-9]+$ ]] && [ "$choice" -ge 1 ] && [ "$choice" -le "${#all_items_ref[@]}" ]; then
local index=$((choice-1))
if ${selected_status_ref[$index]}; then selected_status_ref[index]=false; else selected_status_ref[index]=true; fi
else
echo -e "\n${C_RED}Invalid input. Try again.${C_RESET}"; sleep 2
fi ;;
esac
done
}
interactive_list_builder() {
local title="$1"; local -n source_array="$2"; local -n result_array="$3"
result_array=()
if [[ ${#source_array[@]} -eq 0 ]]; then echo -e "${C_YELLOW}No items found to configure. Skipping.${C_RESET}"; sleep 2; return; fi
local -a selected_status=(); for ((i=0; i<${#source_array[@]}; i++)); do selected_status+=("false"); done
if ! show_selection_menu "$title" "confirm" source_array selected_status; then return; fi
for i in "${!source_array[@]}"; do if ${selected_status[$i]}; then result_array+=("${source_array[$i]}"); fi; done
}
configure_shell_alias() {
check_root
local user_home="/home/${CURRENT_USER}"
local shell_rc=""
local comment_line="# Alias added by Docker Tool Suite"
if [[ -f "${user_home}/.zshrc" ]]; then
shell_rc="${user_home}/.zshrc"
elif [[ -f "${user_home}/.bashrc" ]]; then
shell_rc="${user_home}/.bashrc"
else
echo -e "${C_YELLOW}No shell configuration found. Creating .bashrc...${C_RESET}"
touch "${user_home}/.bashrc"
chown "${CURRENT_USER}:${CURRENT_USER}" "${user_home}/.bashrc"
shell_rc="${user_home}/.bashrc"
fi
clear
echo -e "${C_YELLOW}--- Configure Shell Alias ---${C_RESET}\n"
echo -e "Target User: ${C_GREEN}${CURRENT_USER}${C_RESET}"
echo -e "Config File: ${C_GREEN}${shell_rc}${C_RESET}"
echo -e "Script Path: ${C_CYAN}${SCRIPT_PATH}${C_RESET}\n"
echo "Select an option:"
echo -e " 1) ${C_CYAN}Create or Update Alias${C_RESET}"
echo -e " 2) ${C_RED}Remove Alias${C_RESET}"
echo -e " 3) ${C_YELLOW}Cancel${C_RESET}"
echo
read -rp "${C_YELLOW}Enter choice [${C_RESET}1${C_YELLOW}-${C_RESET}3${C_YELLOW}]: ${C_RESET}" choice
case "$choice" in
1)
local default_alias="dtools"
read -rp "Enter alias name [${C_GREEN}${default_alias}${C_RESET}]: " alias_name
alias_name=${alias_name:-$default_alias}
if [[ ! "$alias_name" =~ ^[a-zA-Z0-9_]+$ ]]; then
echo -e "\n${C_RED}Error: Invalid alias name. Use only letters, numbers, and underscores.${C_RESET}"
echo -e "${C_GRAY}Characters like '/' or spaces are not allowed.${C_RESET}"; sleep 2
return
fi
if grep -q "^alias ${alias_name}=" "$shell_rc" && ! grep -q "^alias ${alias_name}='${SCRIPT_PATH}'" "$shell_rc"; then
echo -e "\n${C_RED}Error: The alias '${alias_name}' is already defined in ${shell_rc} pointing to something else.${C_RESET}"
echo -e "${C_YELLOW}Please choose a different name.${C_RESET}"; sleep 2
return
fi
local new_alias_line="alias ${alias_name}='${SCRIPT_PATH}'"
local temp_rc; temp_rc=$(mktemp)
grep -v -F "$comment_line" "$shell_rc" | grep -v "alias .*='${SCRIPT_PATH}'" > "$temp_rc"
echo "$comment_line" >> "$temp_rc"
echo "$new_alias_line" >> "$temp_rc"
mv "$temp_rc" "$shell_rc"
chown "${CURRENT_USER}:${CURRENT_USER}" "$shell_rc"
echo -e "\n${C_GREEN}${TICKMARK} Alias '${C_CYAN}${alias_name}${C_GREEN}' added to ${C_CYAN}${shell_rc}${C_GREEN}!${C_RESET}"
echo -e "${C_GRAY}NOTE: Run 'source ${shell_rc}' or restart your terminal to use it.${C_RESET}"
;;
2)
if ! grep -q "alias .*='${SCRIPT_PATH}'" "$shell_rc"; then
echo -e "\n${C_YELLOW}No alias found to remove in ${C_GREEN}${shell_rc}${C_YELLOW}.${C_RESET}"
sleep 1; return
fi
echo -e "\n${C_YELLOW}Removing alias...${C_RESET}"
local temp_rc; temp_rc=$(mktemp)
grep -v -F "$comment_line" "$shell_rc" | grep -v "alias .*='${SCRIPT_PATH}'" > "$temp_rc"
mv "$temp_rc" "$shell_rc"
chown "${CURRENT_USER}:${CURRENT_USER}" "$shell_rc"
echo -e "${C_GREEN}${TICKMARK} Alias removed successfully.${C_RESET}"
;;
*) return ;;
esac
}
ensure_tool_installed() {
local tool_cmd="$1"
local package_name="$2"
local tool_desc="$3"
if ! command -v "$tool_cmd" &>/dev/null; then
echo -e "\n${C_RED}Error: '${tool_cmd}' command not found.${C_RESET}"
echo -e "${C_YELLOW}This tool is required for: ${tool_desc}.${C_RESET}\n"
read -rp "${C_YELLOW}Do you want to install '${C_CYAN}${package_name}${C_YELLOW}' now? ${C_RESET}(${C_GREEN}Y${C_RESET}/${C_RED}n${C_RESET}): " install_tool
if [[ "${install_tool:-y}" =~ ^(y|Y|yes|YES)$ ]]; then
echo -e "${C_CYAN}Installing ${package_name}...${C_RESET}"
if $SUDO_CMD apt-get update && $SUDO_CMD apt-get install -y "$package_name"; then
echo -e "${C_GREEN}Installation successful.${C_RESET}"
return 0
else
echo -e "${C_RED}Installation failed. Please install '${C_CYAN}${package_name}${C_RED}' manually.${C_RESET}"
return 1
fi
else
echo -e "${C_RED}Operation cancelled. Missing dependency.${C_RESET}"
return 1
fi
fi
return 0
}
_prompt_input() {
local prompt_text="$1"
local default_val="$2"
local -n output_var="$3"
local val_type="${4:-text}"
local min="${5:-}"
local max="${6:-}"
while true; do
local input_val
read -erp "${prompt_text} [${C_GREEN}${default_val}${C_RESET}]: " input_val
if [[ -z "$input_val" ]]; then
output_var="$default_val"
else
output_var="$input_val"
fi
local valid=true
case "$val_type" in
int)
if [[ ! "$output_var" =~ ^[0-9]+$ ]]; then
echo -e "${C_RED}Error: Input must be a positive integer.${C_RESET}"
valid=false
else
local check_val=$((10#$output_var))
if [[ -n "$min" && "$check_val" -lt "$min" ]]; then
echo -e "${C_RED}Error: Minimum value is $min.${C_RESET}"
valid=false
fi
if [[ -n "$max" && "$check_val" -gt "$max" ]]; then
echo -e "${C_RED}Error: Maximum value is $max.${C_RESET}"
valid=false
fi
fi
;;
path)
if [[ "$output_var" == ~* ]]; then
output_var="${output_var/#\~/$HOME}"
fi
if [[ ! "$output_var" =~ ^/ ]]; then
echo -e "${C_RED}Error: Path must be absolute (start with / or ~).${C_RESET}"
valid=false
fi
if [[ "$output_var" =~ [\&\|\;\`\$] ]]; then
echo -e "${C_RED}Error: Path contains invalid shell characters.${C_RESET}"
valid=false
fi
;;
subdir)
if [[ "$output_var" =~ ^(/|~) ]]; then
echo -e "${C_RED}Error: Subdirectory must be a relative path (cannot start with / or ~).${C_RESET}"
valid=false
fi
if [[ "$output_var" =~ [\&\|\;\`\$] ]]; then
echo -e "${C_RED}Error: Name contains invalid shell characters.${C_RESET}"
valid=false
fi
;;
esac
if $valid; then break; fi
done
}
initial_setup() {
check_root
clear
echo "====================================================="
echo -e "${C_GREEN}${T_BOLD} Welcome to the ${C_CYAN}Docker Tool Suite ${SCRIPT_VERSION} ${C_GREEN}Setup!${C_RESET}"
echo "====================================================="
echo -e "\n${C_YELLOW}--- Checking System Dependencies ---${C_RESET}"
local -a packages_to_install=()
if ! command -v openssl &>/dev/null; then
echo -e " ${C_RED}[-] openssl is missing.${C_RESET}"
packages_to_install+=("openssl")
else
echo -e " ${C_GREEN}[+] openssl is installed.${C_RESET}"
fi
if ! command -v 7z &>/dev/null; then
echo -e " ${C_RED}[-] 7z (p7zip-full) is missing.${C_RESET}"
packages_to_install+=("p7zip-full")
else
echo -e " ${C_GREEN}[+] 7z is installed.${C_RESET}"
fi
if [ ${#packages_to_install[@]} -gt 0 ]; then
echo -e "\n${C_RED}Missing tools detected. These are required for encryption and archives.${C_RESET}"
read -rp "${C_YELLOW}Do you want to install them now via apt? ${C_RESET}(${C_GREEN}Y${C_RESET}/${C_RED}n${C_RESET}): " install_deps
if [[ "${install_deps:-y}" =~ ^(y|Y|yes|YES)$ ]]; then
echo -e "${C_CYAN}Updating package lists and installing...${C_RESET}"
$SUDO_CMD apt-get update
$SUDO_CMD apt-get install -y "${packages_to_install[@]}"
echo -e "${C_GREEN}${TICKMARK} Dependencies installed successfully.${C_RESET}"
else
echo -e "${C_RED}Warning: Script may fail without these dependencies.${C_RESET}"
sleep 2
fi
fi
echo -e "\n${C_YELLOW}This one-time setup will configure all modules.\n"
echo -e "${C_RESET}Settings will be saved to: ${C_GREEN}${CONFIG_FILE}${C_RESET}\n"
local apps_path_def="/home/${CURRENT_USER}/apps"
local managed_subdir_def="managed_stacks"
local backup_path_def="/home/${CURRENT_USER}/backups/docker-volume-backups"
local restore_path_def="/home/${CURRENT_USER}/backups/docker-volume-backups"
local log_dir_def="/home/${CURRENT_USER}/logs/dtools"
local log_retention_def="30"
echo -e "-----------------------------------------------------\n"
echo -e "${C_YELLOW}--- Configure Path Settings ---${C_RESET}\n"
echo -e "${C_GRAY}Leave the default paths or enter your own. Autocompletion (Tab) is enabled.\n${C_RESET}"
_prompt_input "Base Compose Apps Path" "$apps_path_def" APPS_BASE_PATH "path"
_prompt_input "Managed Apps Subdirectory" "$managed_subdir_def" MANAGED_SUBDIR "subdir"
_prompt_input "Volume Backup Location" "$backup_path_def" BACKUP_LOCATION "path"
_prompt_input "Volume Restore Location" "$restore_path_def" RESTORE_LOCATION "path"
_prompt_input "Log Directory Path" "$log_dir_def" LOG_DIR "path"
_prompt_input "Log file retention period in days. Set to 0 to disable automatic pruning." "$log_retention_def" LOG_RETENTION_DAYS "int" 0 3650
local log_sub_update_def="apps-update-logs"
local log_sub_unused_def="unused-images-update-logs"
_prompt_input "Subdirectory for App Update Logs" "$log_sub_update_def" LOG_SUBDIR_UPDATE "subdir"
_prompt_input "Subdirectory for Unused Image Logs" "$log_sub_unused_def" LOG_SUBDIR_UNUSED "subdir"
echo -e "\n${C_YELLOW}--- Configure Helper Images ---${C_RESET}"
local backup_image_def="docker/alpine-tar-zstd:latest"
local explore_image_def="debian:trixie-slim"
_prompt_input "Backup Helper Image" "$backup_image_def" BACKUP_IMAGE "text"
_prompt_input "Volume Explorer Image" "$explore_image_def" EXPLORE_IMAGE "text"
local -a selected_ignored_volumes=()
read -rp $'\n'"${C_YELLOW}Do you want to configure ignored ${C_CYAN}volumes ${C_YELLOW}now? (${C_GREEN}y${C_YELLOW}/${C_RED}N${C_YELLOW})${C_RESET}: " config_vols
if [[ "${config_vols,,}" =~ ^(y|Y|yes|YES)$ ]]; then
mapfile -t all_volumes < <(docker volume ls --format "{{.Name}}" | sort)
interactive_list_builder "Select Volumes to IGNORE during backup" all_volumes selected_ignored_volumes
fi
local -a selected_ignored_images=()
read -rp $'\n'"${C_YELLOW}Do you want to configure ignored ${C_CYAN}images ${C_YELLOW}now? (${C_GREEN}y${C_YELLOW}/${C_RED}N${C_YELLOW})${C_RESET}: " config_imgs
if [[ "${config_imgs,,}" =~ ^(y|Y|yes|YES)$ ]]; then
mapfile -t all_images < <(docker image ls --format "{{.Repository}}:{{.Tag}}" | grep -v "<none>" | sort)
interactive_list_builder "Select Images to IGNORE during updates" all_images selected_ignored_images
fi
echo -e "\n${C_YELLOW}--- Secure Archive Settings ---${C_RESET}"
local archive_pass_1 archive_pass_2 ENCRYPTED_ARCHIVE_PASSWORD=""
while true; do
echo -e "${C_GRAY}This password will be used to encrypt 7z backups by default.${C_RESET}"
read -srp "Enter a default password (leave blank for none): " archive_pass_1; echo
if [[ -z "$archive_pass_1" ]]; then
read -rp "${C_RED}You left the password blank! ${C_YELLOW}Disable default encryption? (${C_RED}Y${C_YELLOW}/${C_GREEN}n${C_YELLOW}): ${C_RESET}" confirm_no_pass
if [[ "${confirm_no_pass:-y}" =~ ^[Yy]$ ]]; then
echo -e "${C_GREEN}-> Default encryption disabled.${C_RESET}"
ENCRYPTED_ARCHIVE_PASSWORD=""
break
else
echo -e "${C_CYAN}-> Please enter a password then.${C_RESET}"
continue
fi
fi
read -srp "Confirm password: " archive_pass_2; echo
if [[ "$archive_pass_1" == "$archive_pass_2" ]]; then
ENCRYPTED_ARCHIVE_PASSWORD=$(encrypt_pass "${archive_pass_1}")
echo -e "${C_GREEN}-> Password saved and encrypted.${C_RESET}"
break
else
echo -e "${C_RED}Passwords do not match. Please try again.${C_RESET}"
fi
done
_prompt_input "${C_YELLOW}Default 7z Compression Level ${C_CYAN}(Copy:0 - Ultra:9)${C_RESET}" "3" ARCHIVE_COMPRESSION_LEVEL "int" 0 9
clear
echo -e "\n${C_GREEN}_--| Docker Tool Suite ${SCRIPT_VERSION} Setup |---_${C_RESET}\n"
echo -e "${C_YELLOW}--- Configuration Summary ---${C_RESET}\n"
echo " App Manager:"
echo -e " Base Path: ${C_GREEN}${APPS_BASE_PATH}${C_RESET}"
echo -e " Managed Subdir: ${C_GREEN}${MANAGED_SUBDIR}${C_RESET}"
echo " Volume Manager:"
echo -e " Backup Path: ${C_GREEN}${BACKUP_LOCATION}${C_RESET}"
echo -e " Restore Path: ${C_GREEN}${RESTORE_LOCATION}${C_RESET}"
echo -e " Backup Image: ${C_GREEN}${BACKUP_IMAGE}${C_RESET}"
echo -e " Explorer Image: ${C_GREEN}${EXPLORE_IMAGE}${C_RESET}"
echo " Archive Settings:"
echo -e " Compress Level: ${C_GREEN}${ARCHIVE_COMPRESSION_LEVEL}${C_RESET}"
echo " Logs:"
echo -e " Log Path: ${C_GREEN}${LOG_DIR}${C_RESET}"
echo -e " Log Retention: ${C_GREEN}${LOG_RETENTION_DAYS} days${C_RESET}"
echo " Ignored Items:"
echo -e " Volumes: ${C_GREEN}${#selected_ignored_volumes[@]} selected${C_RESET}"
echo -e " Images: ${C_GREEN}${#selected_ignored_images[@]} selected${C_RESET}\n"
read -rp "${C_YELLOW}Save this configuration? ${C_RESET}(${C_GREEN}Y${C_RESET}/${C_RED}n${C_RESET}): " confirm_setup
if [[ ! "${confirm_setup,,}" =~ ^(y|Y|yes|YES)$ ]]; then echo -e "\n ${C_RED}Setup canceled!\n${C_GRAY}(confirm to save the config)${C_RESET}"; exit 0; fi
echo -e "\n${C_GREEN}Saving configuration...${C_RESET}"; mkdir -p "${CONFIG_DIR}"
{
echo "# ============================================="
echo "# Unified Configuration for Docker Tool Suite"
echo "# ============================================="
echo
echo "# App Directories"
printf "APPS_BASE_PATH=\"%s\"\n" "${APPS_BASE_PATH}"
printf "MANAGED_SUBDIR=\"%s\"\n" "${MANAGED_SUBDIR}"
echo
echo "# Backup Directories"
printf "BACKUP_LOCATION=\"%s\"\n" "${BACKUP_LOCATION}"
printf "RESTORE_LOCATION=\"%s\"\n" "${RESTORE_LOCATION}"
echo ""
echo "# Image used for backup/restore operations (must have tar and zstd)"
printf "BACKUP_IMAGE=\"%s\"\n" "${BACKUP_IMAGE}"
echo "# Image used for the interactive shell explorer"
printf "EXPLORE_IMAGE=\"%s\"\n" "${EXPLORE_IMAGE}"
echo
echo "# List of volumes to ignore during operations."
echo -n "IGNORED_VOLUMES=("
if [ ${#selected_ignored_volumes[@]} -gt 0 ]; then
printf "\n"; for vol in "${selected_ignored_volumes[@]}"; do echo " \"$vol\""; done
else
printf "\n"; echo " \"example-of-ignored_volume-1\""
printf ""; echo " \"example-of-ignored_volume-2\""
printf ""; echo " \"example-of-ignored_volume-3\""
fi
echo ")"
echo
echo "# List of images to ignore during operations."
echo -n "IGNORED_IMAGES=("
if [ ${#selected_ignored_images[@]} -gt 0 ]; then
printf "\n"; for img in "${selected_ignored_images[@]}"; do echo " \"$img\""; done
else
printf "\n"; echo " \"custom-registry/my-custom-app-1:latest\""
printf ""; echo " \"custom-registry/my-custom-app-2:latest\""
printf ""; echo " \"custom-registry/my-custom-app-3:latest\""
fi
echo ")"
echo
echo "# Archive Settings"
echo "# Password is encrypted using a unique key stored in .master.key."
printf "ENCRYPTED_ARCHIVE_PASSWORD=%q\n" "${ENCRYPTED_ARCHIVE_PASSWORD}"
echo "# Map compression: 7z levels are 0-9. (mx=0 is copy, mx=9 is ultra)."
echo "ARCHIVE_COMPRESSION_LEVEL=\"${ARCHIVE_COMPRESSION_LEVEL}\""
echo
echo "# Log Settings"
printf "LOG_DIR=\"%s\"\n" "${LOG_DIR}"
printf "LOG_SUBDIR_UPDATE=\"%s\"\n" "${LOG_SUBDIR_UPDATE}"
printf "LOG_SUBDIR_UNUSED=\"%s\"\n" "${LOG_SUBDIR_UNUSED}"
echo "# Log file retention period in days. Set to 0 to disable automatic pruning."
printf "LOG_RETENTION_DAYS=%s\n" "\"${LOG_RETENTION_DAYS}\""
} > "${CONFIG_FILE}"
echo -e "${C_YELLOW}Creating directories and setting permissions...${C_RESET}"
mkdir -p "${APPS_BASE_PATH}/${MANAGED_SUBDIR}" "${BACKUP_LOCATION}" "${RESTORE_LOCATION}" "${LOG_DIR}"
$SUDO_CMD chown -R "${CURRENT_USER}:${CURRENT_USER}" "${CONFIG_DIR}" "${APPS_BASE_PATH}" "${BACKUP_LOCATION}" "${RESTORE_LOCATION}" "${LOG_DIR}"
# Restrict Config Permissions
chmod 700 "${CONFIG_DIR}"
chmod 600 "${CONFIG_FILE}"
# Prompt for Task Scheduler
echo -e "\n${C_GREEN}--- Task Scheduler ---${C_RESET}\n"
read -rp "${C_YELLOW}Do you want to configure scheduled tasks ${C_GRAY}(Auto-Updates) ${C_YELLOW}now? ${C_RESET}(${C_CYAN}y${C_RESET}/${C_RED}N${C_RESET}): " config_sched
if [[ "${config_sched,,}" =~ ^(y|Y|yes|YES)$ ]]; then
scheduler_menu
fi
# Prompt for Shell Alias
echo -e "\n${C_GREEN}--- Optional: Shell Shortcut ---${C_RESET}\n"
read -rp "${C_YELLOW}Do you want to create a shell shortcut ${C_GRAY}(alias) ${C_YELLOW}now? ${C_RESET}(${C_CYAN}y${C_RESET}/${C_RED}N${C_RESET}): " config_alias
if [[ "${config_alias,,}" =~ ^(y|Y|yes|YES)$ ]]; then
configure_shell_alias
fi
echo -e "\n${C_GREEN}${TICKMARK} Setup complete! The script will now continue.${C_RESET}\n"; sleep 2
}
install_autocompletion() {
check_root
local user_home="/home/${CURRENT_USER}"
local shell_rc=""
local shell_type=""
# Detect Shell via Parent Process
local parent_process
parent_process=$(ps -o comm= -p $PPID 2>/dev/null || echo "$SHELL")
if [[ "$parent_process" =~ "zsh" ]]; then
shell_rc="${user_home}/.zshrc"
shell_type="zsh"
elif [[ "$parent_process" =~ "bash" ]]; then
shell_rc="${user_home}/.bashrc"
shell_type="bash"
else
echo -e "${C_RED}Could not detect supported shell (Bash/Zsh).${C_RESET}"
return 1
fi
echo -e "${C_YELLOW}Detected shell: ${C_CYAN}${shell_type}${C_YELLOW} | Config: ${C_CYAN}${shell_rc}${C_RESET}"
# Prepare Paths for injection
local apps_dir="${APPS_BASE_PATH}"
local managed_dir="${APPS_BASE_PATH}/${MANAGED_SUBDIR}"
# Prepare Content
local new_content
new_content="# >>> Dtools Autocompletion >>>"
new_content+=$'\n'
if [[ "$shell_type" == "zsh" ]]; then
# --- ZSH VERSION ---
# We inject the literal paths so Zsh knows where to look for folders
new_content+=$(cat <<EOF
#compdef dtools
_dtools() {
local context state line
typeset -A opt_args
_arguments -C \\
'1: :->cmds' \\
'*:: :->args'
case \$state in
cmds)
local -a commands
commands=(
'update:Update specific or all apps'
'update-unused:Update unused images'
'--quick-backup:Backup specific volumes'
'-qb:Backup specific volumes'
'--help:Show help'
'-h:Show help'
'--version:Show version'
'-v:Show version'
)
_describe 'command' commands
;;
args)
case \$line[1] in
update)
# Complete folder names from both App dirs
_path_files -W "(${apps_dir} ${managed_dir})" -/
;;
--quick-backup|-qb)
local -a volumes
volumes=("\${(@f)\$(docker volume ls -q 2>/dev/null)}")
# _alternative allows us to present multiple types of completion at once.
# 1. Docker Volumes (using compadd)
# 2. Files/Directories (using _files)
_alternative \\
"volumes:Docker Volume:compadd -a volumes" \\
"files:Filename:_files"
;;
*)
# For all other commands, default to file completion
_files
;;
esac
;;
esac
}
compdef _dtools dtools docker_tool_suite.sh
EOF
)
else
# --- BASH VERSION ---
# We inject a 'find' command to list folders in your app directories
new_content+=$(cat <<EOF
_dtools_completions() {
local cur prev opts
COMPREPLY=()
cur="\${COMP_WORDS[COMP_CWORD]}"
prev="\${COMP_WORDS[COMP_CWORD-1]}"
opts="update update-unused --quick-backup -qb --help -h --version -v"
# Check if 'update' is the command being used
if [[ " \${COMP_WORDS[@]} " =~ " update " ]]; then
local apps
# List directories from both locations, strip paths to just names
apps=\$(find "${apps_dir}" "${managed_dir}" -mindepth 1 -maxdepth 1 -type d -printf "%f\n" 2>/dev/null)
COMPREPLY=( \$(compgen -W "\${apps} --all --dry-run" -- \${cur}) )
return 0
fi
local is_qb=false
for ((i=1; i < COMP_CWORD; i++)); do
if [[ "\${COMP_WORDS[i]}" == "-qb" || "\${COMP_WORDS[i]}" == "--quick-backup" ]]; then
is_qb=true
break
fi
done
if [[ "\$is_qb" == "true" ]]; then
local volumes
volumes=\$(docker volume ls -q 2>/dev/null)
COMPREPLY=( \$(compgen -W "\${volumes}" -- \${cur}) )
while IFS= read -r f; do
COMPREPLY+=( "\$f" )
done < <(compgen -f -- "\${cur}")
return 0
fi
if [[ \${cur} == -* ]] || [[ \${COMP_CWORD} -eq 1 ]]; then
COMPREPLY=( \$(compgen -W "\${opts}" -- \${cur}) )
return 0
fi
}
complete -F _dtools_completions dtools
EOF
)
fi
new_content+=$'\n'
new_content+="# <<< Dtools Autocompletion <<<"
# Installation Logic
if grep -Fq "# >>> Dtools Autocompletion >>>" "$shell_rc"; then
echo -e "${C_YELLOW}Updating existing autocompletion block (in-place)...${C_RESET}"
local temp_rc; temp_rc=$(mktemp)
awk -v new_block="$new_content" '
BEGIN { printing=1 }
/^# >>> Dtools Autocompletion >>>/ { printing=0; print new_block; next }
/^# <<< Dtools Autocompletion <<</ { printing=1; next }
printing { print }
' "$shell_rc" > "$temp_rc"
cat "$temp_rc" > "$shell_rc"
rm "$temp_rc"
else
echo -e "${C_YELLOW}Appending new autocompletion block...${C_RESET}"
[ -n "$(tail -c1 "$shell_rc")" ] && echo "" >> "$shell_rc"
echo "$new_content" >> "$shell_rc"
fi
echo -e "${C_GREEN}${TICKMARK} Autocompletion installed/updated!${C_RESET}"
echo -e "${C_GRAY}Please run 'source ${shell_rc}' (or restart terminal) to apply changes.${C_RESET}"
}
validate_and_edit_compose() {
local app_name="$1"
local file="$2"
# Simple validation: ensure the file actually exists
if [[ ! -f "$file" ]]; then
log "Error: Compose file for '$app_name' not found."
echo -e "${C_RED}Error: Compose file not found: $file${C_RESET}"
return 1
fi
return 0
}
_start_app_task() {
local app_name="$1" app_dir="$2"
local extra_args="${3:-}"
log "Starting $app_name..."
local compose_file; compose_file=$(find_compose_file "$app_dir")
if [ -z "$compose_file" ]; then log "Warning: No compose file for '$app_name'. Skipping." ""; return; fi
if ! validate_and_edit_compose "$app_name" "$compose_file"; then return; fi
log "Starting containers for '$app_name' (Args: ${extra_args:-none})..."
if execute_and_log $SUDO_CMD docker compose -f "$compose_file" up -d $extra_args; then
log "Successfully started '$app_name'."
echo -e "${C_GREEN}Successfully started '${C_CYAN}$app_name${C_GREEN}'.${C_RESET}"
else
log "ERROR: Failed to start '$app_name'."
echo -e "${C_RED}Failed to start '${C_CYAN}$app_name${C_RED}'! Check log for details.${C_RESET}"
fi
}
_stop_app_task() {
local app_name="$1" app_dir="$2"
log "Stopping $app_name..."
local compose_file; compose_file=$(find_compose_file "$app_dir")
if [ -z "$compose_file" ]; then log "Info: No compose file for '$app_name'. Cannot stop." ""; return; fi
if ! validate_and_edit_compose "$app_name" "$compose_file"; then return; fi
if execute_and_log $SUDO_CMD docker compose -f "$compose_file" down --remove-orphans; then
log "Successfully stopped '$app_name'."