Repository navigation
Expand file tree
/
Copy pathinstall.sh
More file actions
6316 lines (5642 loc) · 246 KB
/
Copy pathinstall.sh
File metadata and controls
6316 lines (5642 loc) · 246 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
set -o pipefail
if locale -a 2>/dev/null | grep -qi '^C\.utf8$'; then
export LC_ALL=C.UTF-8
elif locale -a 2>/dev/null | grep -qi '^C\.UTF-8$'; then
export LC_ALL=C.UTF-8
fi
readonly FAOXIMA_VERSION="1.2.0"
readonly FAOXIMA_REPO="Mmd-Amir/Faoxima"
readonly FAOXIMA_GITHUB="https://github.com/${FAOXIMA_REPO}"
readonly FAOXIMA_TELEGRAM="https://t.me/faoxima"
readonly DEFAULT_PROJECT_DIR="/opt/faoxima"
_script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly STAGING_SOURCE_DIR="$_script_dir"
if [ "$_script_dir" = "$DEFAULT_PROJECT_DIR" ] && { [ -f "${_script_dir}/docker-compose.yml" ] || [ -f "${_script_dir}/config.php" ]; }; then
readonly PROJECT_DIR="$_script_dir"
else
readonly PROJECT_DIR="$DEFAULT_PROJECT_DIR"
fi
unset _script_dir
readonly BOT_DIR="$PROJECT_DIR"
readonly COMPOSE_FILE="${PROJECT_DIR}/docker-compose.yml"
readonly ENV_FILE="${PROJECT_DIR}/.env"
readonly ENV_EXAMPLE="${PROJECT_DIR}/.env.example"
readonly LOG_FILE="/var/log/faoxima_installer.log"
readonly TMP_DOWNLOAD="/tmp/faoxima_download"
readonly TMP_UPDATE="/tmp/faoxima_update"
readonly CACHE_DIR="/tmp/faoxima_menu_cache"
readonly DEFAULT_DB_NAME="faoxima"
readonly INSTALL_SCRIPT_PATH="${PROJECT_DIR}/install.sh"
readonly INSTALL_SCRIPT_LINK="/usr/local/bin/faoxima"
readonly NGINX_CONF_DIR="${PROJECT_DIR}/nginx/conf.d"
readonly NGINX_TEMPLATE="${PROJECT_DIR}/docker/nginx/nginx.conf.template"
readonly BOT_NGINX_TEMPLATE="${PROJECT_DIR}/docker/nginx/bot.conf.template"
readonly NGINX_BOTS_CONF_DIR="${PROJECT_DIR}/nginx/conf.d/bots"
readonly BOTS_DIR="$(dirname "$PROJECT_DIR")/bots"
readonly CONTAINER_APP_DIR="/var/www/faoxima"
readonly BOT_COMPOSE_PREFIX="${PROJECT_DIR}/docker-compose.bot-"
if [ "$(id -u)" -ne 0 ]; then
printf '\033[1;31m[ERROR]\033[0m This script must be run as \033[1mroot\033[0m.\n' >&2
exit 1
fi
readonly C_RESET=$'\033[0m'
readonly C_BOLD=$'\033[1m'
readonly C_DIM=$'\033[2m'
readonly C_RED=$'\033[1;31m'
readonly C_GREEN=$'\033[1;32m'
readonly C_YELLOW=$'\033[1;33m'
readonly C_BLUE=$'\033[1;34m'
readonly C_MAGENTA=$'\033[1;35m'
readonly C_CYAN=$'\033[1;36m'
readonly C_WHITE=$'\033[1;37m'
readonly C_GRAY=$'\033[38;5;245m'
readonly C_PINK=$'\033[38;5;205m'
readonly C_ORANGE=$'\033[38;5;215m'
ui_term_width() {
if [ -n "$UI_FIXED_WIDTH" ]; then
printf '%d' "$UI_FIXED_WIDTH"
return
fi
local w
w=$(tput cols 2>/dev/null || echo 80)
[[ -z "$w" || "$w" -lt 60 ]] && w=80
[[ "$w" -gt 110 ]] && w=110
printf '%d' "$w"
}
ui_strlen() {
local stripped
stripped=$(printf '%s' "$1" | sed -E $'s/\033\\[[0-9;]*[A-Za-z]//g')
printf '%d' "${#stripped}"
}
ui_content_width() {
local title="$1" min_content="${#title}" line len term_w
shift
for line in "$@"; do
len=$(ui_strlen "$line")
[ "$len" -gt "$min_content" ] && min_content=$len
done
term_w=$(ui_term_width)
local wanted=$((min_content + 6))
[ "$wanted" -lt 40 ] && wanted=40
[ "$wanted" -gt "$term_w" ] && wanted=$term_w
printf '%d' "$wanted"
}
ui_wrap_line() {
local line="$1" max_len="$2"
local prefix="" suffix="" plain="$line"
if [[ "$line" =~ ^($'\033'\[[0-9\;]*m)(.*)$ ]]; then
prefix="${BASH_REMATCH[1]}"
plain="${BASH_REMATCH[2]}"
fi
if [[ "$plain" == *$'\033['*m ]]; then
suffix=$(printf '%s' "$plain" | grep -oE $'\033\\[[0-9;]*m' | tail -1)
plain=$(printf '%s' "$plain" | sed -E $'s/\033\\[[0-9;]*m//g')
fi
if [ "${#plain}" -le "$max_len" ]; then
printf '%s\n' "$line"
return
fi
local word cur=""
for word in $plain; do
if [ -z "$cur" ]; then
cur="$word"
elif [ "$(( ${#cur} + 1 + ${#word} ))" -le "$max_len" ]; then
cur="${cur} ${word}"
else
printf '%s%s%s\n' "$prefix" "$cur" "$suffix"
cur="$word"
fi
done
[ -n "$cur" ] && printf '%s%s%s\n' "$prefix" "$cur" "$suffix"
}
ui_repeat() {
local ch="$1" n="$2" out="" i=0
while [ "$i" -lt "$n" ]; do
out+="$ch"
i=$((i + 1))
done
printf '%s' "$out"
}
ui_spaces() { printf '%*s' "$1" ''; }
ui_box_top() {
local title="$1" title_color="$2" border_color="$3" width="$4"
local inner=$((width - 2))
local title_text=" ${title} "
local title_len=${#title_text}
local pad_left=$(( (inner - title_len) / 2 ))
local pad_right=$(( inner - title_len - pad_left ))
[ "$pad_left" -lt 1 ] && pad_left=1
[ "$pad_right" -lt 1 ] && pad_right=1
printf '%s╭%s%s%s%s%s%s%s%s╮%s\n' \
"$border_color" \
"$(ui_repeat '─' "$pad_left")" \
"$C_RESET" "$title_color" "$title_text" "$C_RESET" "$border_color" \
"$(ui_repeat '─' "$pad_right")" "$C_RESET" \
"$C_RESET"
}
ui_box_top_plain() {
local border_color="$1" width="$2"
printf '%s╭%s╮%s\n' "$border_color" "$(ui_repeat '─' $((width - 2)))" "$C_RESET"
}
ui_box_blank() {
local border_color="$1" width="$2"
printf '%s│%s│%s\n' "$border_color" "$(ui_spaces $((width - 2)))" "$C_RESET"
}
ui_box_line() {
local border_color="$1" width="$2" content="$3"
local inner=$((width - 4))
local visible_len pad
visible_len=$(ui_strlen "$content")
pad=$((inner - visible_len))
[ "$pad" -lt 0 ] && pad=0
printf '%s│%s %b%s %s│%s\n' \
"$border_color" "$C_RESET" \
"$content" "$(ui_spaces $pad)" \
"$border_color" "$C_RESET"
}
ui_box_divider() {
local border_color="$1" width="$2"
printf '%s├%s┤%s\n' "$border_color" "$(ui_repeat '─' $((width - 2)))" "$C_RESET"
}
ui_box_bottom() {
local border_color="$1" width="$2"
printf '%s╰%s╯%s\n' "$border_color" "$(ui_repeat '─' $((width - 2)))" "$C_RESET"
}
ui_panel() {
local title="$1" title_color="$2" border_color="$3"
shift 3
local term_w max_w=90
term_w=$(ui_term_width)
[ "$term_w" -lt "$max_w" ] && max_w=$term_w
local wrapped_lines=() line wrapped
for line in "$@"; do
wrapped=$(ui_wrap_line "$line" $((max_w - 6)))
while IFS= read -r w; do
wrapped_lines+=("$w")
done <<< "$wrapped"
done
local width
width=$(ui_content_width "$title" "${wrapped_lines[@]}")
ui_box_top "$title" "$title_color" "$border_color" "$width"
ui_box_blank "$border_color" "$width"
for line in "${wrapped_lines[@]}"; do
ui_box_line "$border_color" "$width" "$line"
done
ui_box_blank "$border_color" "$width"
ui_box_bottom "$border_color" "$width"
}
ui_tip() {
local message="$1"
local width
width=$(ui_term_width)
ui_box_top_plain "$C_GREEN" "$width"
ui_box_line "$C_GREEN" "$width" "${C_GREEN}${C_BOLD}Tip:${C_RESET} ${message}"
ui_box_bottom "$C_GREEN" "$width"
}
ui_status_table() {
local title="$1" border_color="$2"
shift 2
local pair key val key_w=0
for pair in "$@"; do
key="${pair%%|*}"
[ "${#key}" -gt "$key_w" ] && key_w=${#key}
done
[ "$key_w" -gt 24 ] && key_w=24
local rendered_lines=() padded_key
for pair in "$@"; do
key="${pair%%|*}"
val="${pair#*|}"
padded_key=$(printf '%-*s' "$key_w" "$key")
rendered_lines+=("${C_CYAN}${padded_key}${C_RESET} ${C_WHITE}${val}${C_RESET}")
done
local width
width=$(ui_content_width "$title" "${rendered_lines[@]}")
ui_box_top "$title" "$C_CYAN" "$border_color" "$width"
ui_box_blank "$border_color" "$width"
local line
for line in "${rendered_lines[@]}"; do
ui_box_line "$border_color" "$width" "$line"
done
ui_box_blank "$border_color" "$width"
ui_box_bottom "$border_color" "$width"
}
ui_section() {
local title="$1"
shift
printf '%s│%s %s%s%s\n' "$C_ORANGE" "$C_RESET" "$C_BOLD" "$title" "$C_RESET"
printf '%s%s%s\n' "$C_BLUE" "$(ui_repeat '─' 60)" "$C_RESET"
printf '\n'
local key_w=0 pair key
for pair in "$@"; do
key="${pair%%|*}"
[ "${#key}" -gt "$key_w" ] && key_w=${#key}
done
local val padded_key
for pair in "$@"; do
key="${pair%%|*}"
val="${pair#*|}"
padded_key=$(printf '%-*s' "$key_w" "$key")
printf ' %s%s%s : %b\n' "$C_CYAN" "$padded_key" "$C_RESET" "$val"
done
printf '\n'
}
ui_menu_list() {
local title="$1"
shift
printf '%s│%s %s%s%s\n' "$C_ORANGE" "$C_RESET" "$C_BOLD" "$title" "$C_RESET"
printf '%s%s%s\n' "$C_BLUE" "$(ui_repeat '─' 60)" "$C_RESET"
printf '\n'
local item
for item in "$@"; do
printf ' %b\n' "$item"
done
printf '\n'
}
ui_pick_from_list() {
local prompt_label="$1"
shift
local items=("$@")
local total="${#items[@]}"
local page_size=20
local page=0
local last_page=$(( (total - 1) / page_size ))
while true; do
local start=$((page * page_size))
local end=$((start + page_size))
[ "$end" -gt "$total" ] && end="$total"
printf '\n'
local i
for ((i = start; i < end; i++)); do
printf ' %s%2d)%s %s\n' "$C_YELLOW" "$((i + 1))" "$C_RESET" "${items[$i]}"
done
if [ "$last_page" -gt 0 ]; then
printf '\n %s(page %d of %d)%s\n' "$C_DIM" "$((page + 1))" "$((last_page + 1))" "$C_RESET"
fi
local nav_hint=""
[ "$page" -lt "$last_page" ] && nav_hint="${nav_hint}n) next page "
[ "$page" -gt 0 ] && nav_hint="${nav_hint}p) previous page "
printf '\n %s❯%s %s (%sEnter to cancel): ' "$C_YELLOW" "$C_RESET" "$prompt_label" "$nav_hint"
local pick
read -r pick
case "$pick" in
"")
UI_PICK_RESULT=""
return 1
;;
n|N)
if [ "$page" -lt "$last_page" ]; then
page=$((page + 1))
fi
continue
;;
p|P)
if [ "$page" -gt 0 ]; then
page=$((page - 1))
fi
continue
;;
esac
if [[ ! "$pick" =~ ^[0-9]+$ ]] || [ "$pick" -lt 1 ] || [ "$pick" -gt "$total" ]; then
ui_err "Invalid selection."
continue
fi
UI_PICK_RESULT=$((pick - 1))
return 0
done
}
ui_info() { printf ' %s●%s %s\n' "$C_BLUE" "$C_RESET" "$*"; }
ui_ok() { printf ' %s✓%s %s\n' "$C_GREEN" "$C_RESET" "$*"; }
ui_warn() { printf ' %s!%s %s\n' "$C_YELLOW" "$C_RESET" "$*"; }
ui_err() { printf ' %s✗%s %s\n' "$C_RED" "$C_RESET" "$*"; }
ui_action() { printf ' %s→%s %s\n' "$C_CYAN" "$C_RESET" "$*"; }
ui_rule() {
local width
width=$(ui_term_width)
printf '%s%s%s\n' "$C_GRAY" "$(ui_repeat '─' "$width")" "$C_RESET"
}
init_logging() {
local log_dir
log_dir="$(dirname "$LOG_FILE")"
[ -d "$log_dir" ] || mkdir -p "$log_dir"
[ -f "$LOG_FILE" ] || touch "$LOG_FILE"
chmod 600 "$LOG_FILE" 2>/dev/null || true
}
log_message() {
local level="$1"; shift
local message="$*"
local timestamp color
timestamp="$(date '+%Y-%m-%d %H:%M:%S')"
case "$level" in
INFO) color="$C_BLUE" ;;
WARN) color="$C_YELLOW" ;;
ERROR) color="$C_RED" ;;
ACTION) color="$C_CYAN" ;;
*) color="$C_RESET" ;;
esac
printf '%s[%s]%s %s\n' "$color" "$level" "$C_RESET" "$message"
printf '%s [%s] %s\n' "$timestamp" "$level" "$message" >>"$LOG_FILE" 2>/dev/null || true
}
log_action() { log_message "ACTION" "$@"; }
log_info() { log_message "INFO" "$@"; }
log_warn() { log_message "WARN" "$@"; }
log_error() { log_message "ERROR" "$@"; }
init_logging
log_info "Faoxima installer ${FAOXIMA_VERSION} initialized (PID $$)"
get_installed_version() {
local installed_version
installed_version=$(env_get FAOXIMA_INSTALLED_VERSION 2>/dev/null)
if [ -z "$installed_version" ] && [ -f "${PROJECT_DIR}/version" ]; then
installed_version=$(tr -d '[:space:]' < "${PROJECT_DIR}/version")
fi
[ -n "$installed_version" ] && printf '%s' "$installed_version" || printf '%s' "$FAOXIMA_VERSION"
}
resolve_source_version() {
local source="$1" arg1="$2" arg2="$3" code_dir="$4" resolved=""
if [ "$source" = "github" ]; then
if [[ "$arg1" == "-beta" ]] || [[ "$arg1" == "-v" && "$arg2" == "beta" ]]; then
resolved="beta"
elif [[ "$arg1" == "-v" && -n "$arg2" ]]; then
resolved="$arg2"
else
resolved=$(get_latest_version)
fi
elif [ -f "${code_dir}/version" ]; then
resolved=$(tr -d '[:space:]' < "${code_dir}/version")
fi
[[ -z "$resolved" || "$resolved" == "unknown" ]] && resolved="$FAOXIMA_VERSION"
printf '%s' "$resolved"
}
version_is_newer() {
local candidate="${1#v}" installed="${2#v}"
[[ "$candidate" =~ ^[0-9]+([.][0-9]+)*$ ]] || return 1
[[ "$installed" =~ ^[0-9]+([.][0-9]+)*$ ]] || return 1
[ "$candidate" != "$installed" ] && [ "$(printf '%s\n%s\n' "$candidate" "$installed" | sort -V | tail -1)" = "$candidate" ]
}
normalize_version_value() {
local version="$1"
version=$(printf '%s' "$version" | tr -d '[:space:]')
if [ "$version" = "beta" ]; then
printf '%s' "$version"
return 0
fi
if [[ "$version" =~ ^v?[0-9]+([.][0-9]+)*([.-][A-Za-z0-9._-]+)?$ ]]; then
[[ "$version" == v* ]] || version="v${version}"
printf '%s' "$version"
return 0
fi
return 1
}
write_source_version_marker() {
local code_dir="$1" version="$2" marker tmp
version=$(normalize_version_value "$version" 2>/dev/null) || return 1
marker="${code_dir}/.faoxima-version"
tmp="${marker}.tmp.$$"
umask 022
printf '%s\n' "$version" > "$tmp" || { rm -f "$tmp"; return 1; }
chmod 0644 "$tmp" 2>/dev/null || true
mv -f "$tmp" "$marker" || { rm -f "$tmp"; return 1; }
}
read_source_version_marker() {
local code_dir="$1" version=""
[ -f "${code_dir}/.faoxima-version" ] || return 1
version=$(head -n 1 "${code_dir}/.faoxima-version" 2>/dev/null | tr -d '[:space:]')
normalize_version_value "$version"
}
show_animated_logo() {
local latest_line="$1"
clear
printf '\n'
printf '%s███████╗ █████╗ ██████╗ ██╗ ██╗ ██╗ ███╗ ███╗ █████╗ %s\n' "$C_GREEN" "$C_RESET"
printf '%s██╔════╝ ██╔══██╗ ██╔═══██╗ ╚██╗██╔╝ ██║ ████╗ ████║ ██╔══██╗%s\n' "$C_GREEN" "$C_RESET"
printf '%s█████╗ ███████║ ██║ ██║ ╚███╔╝ ██║ ██╔████╔██║ ███████║%s\n' "$C_WHITE" "$C_RESET"
printf '%s██╔══╝ ██╔══██║ ██║ ██║ ██╔██╗ ██║ ██║╚██╔╝██║ ██╔══██║%s\n' "$C_WHITE" "$C_RESET"
printf '%s██║ ██║ ██║ ╚██████╔╝ ██╔╝ ██╗ ██║ ██║ ╚═╝ ██║ ██║ ██║%s\n' "$C_RED" "$C_RESET"
printf '%s╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝%s\n' "$C_RED" "$C_RESET"
printf '\n'
local width=55
local installed_version
installed_version=$(get_installed_version)
ui_box_top "Version" "$C_ORANGE$C_BOLD" "$C_ORANGE" "$width"
ui_box_blank "$C_ORANGE" "$width"
ui_box_line "$C_ORANGE" "$width" "${C_CYAN}Installed${C_RESET} : ${C_GREEN}${installed_version}${C_RESET}"
[ -n "$latest_line" ] && ui_box_line "$C_ORANGE" "$width" "$latest_line"
ui_box_line "$C_ORANGE" "$width" "${C_CYAN}GitHub${C_RESET} : ${C_WHITE}${FAOXIMA_GITHUB}${C_RESET}"
ui_box_line "$C_ORANGE" "$width" "${C_CYAN}Telegram${C_RESET} : ${C_WHITE}${FAOXIMA_TELEGRAM}${C_RESET}"
ui_box_bottom "$C_ORANGE" "$width"
printf '\n'
}
show_logo() { show_animated_logo "$@"; }
dc() {
local files=(-f "$COMPOSE_FILE") f
for f in "${BOT_COMPOSE_PREFIX}"*.yml; do
[ -f "$f" ] && files+=(-f "$f")
done
[ "$(env_get PMA_ENABLED 2>/dev/null)" = "1" ] && files+=(--profile phpmyadmin)
docker compose "${files[@]}" --env-file "$ENV_FILE" "$@"
}
normalize_domain() {
local domain="${1:-}"
domain=$(printf '%s' "$domain" | sed -E 's/^[[:space:]]+//; s/[[:space:]]+$//' | tr '[:upper:]' '[:lower:]')
while [[ "$domain" == *. ]]; do
domain="${domain%.}"
done
printf '%s' "$domain"
}
validate_domain_format() {
local domain
domain=$(normalize_domain "$1")
DOMAIN_VALIDATION_ERROR=""
if [ -z "$domain" ]; then
DOMAIN_VALIDATION_ERROR="Domain cannot be empty."
return 1
fi
if [ "${#domain}" -gt 253 ]; then
DOMAIN_VALIDATION_ERROR="Domain is too long."
return 1
fi
if [[ "$domain" == *://* || "$domain" == */* || "$domain" == *:* || "$domain" == *@* ]]; then
DOMAIN_VALIDATION_ERROR="Enter only the hostname, without http://, https://, port, path, or credentials."
return 1
fi
if [[ "$domain" != *.* ]]; then
DOMAIN_VALIDATION_ERROR="Domain must contain at least one dot."
return 1
fi
local len half first second
len=${#domain}
if [ $((len % 2)) -eq 0 ]; then
half=$((len / 2))
first="${domain:0:half}"
second="${domain:half}"
if [ "$first" = "$second" ]; then
DOMAIN_VALIDATION_ERROR="Domain appears to be duplicated: ${domain}"
return 1
fi
fi
local labels=() label
IFS='.' read -r -a labels <<< "$domain"
if [ "${#labels[@]}" -lt 2 ]; then
DOMAIN_VALIDATION_ERROR="Invalid domain format."
return 1
fi
for label in "${labels[@]}"; do
if [ -z "$label" ] || [ "${#label}" -gt 63 ] || [[ ! "$label" =~ ^[a-z0-9]([a-z0-9-]*[a-z0-9])?$ ]]; then
DOMAIN_VALIDATION_ERROR="Invalid domain label: ${label:-<empty>}"
return 1
fi
done
return 0
}
domain_resolves() {
local domain
domain=$(normalize_domain "$1")
getent ahosts "$domain" >/dev/null 2>&1 || getent hosts "$domain" >/dev/null 2>&1
}
get_cert_enddate() {
local domain
domain=$(normalize_domain "$1")
local project volume_name mountpoint cert_path
project=$(env_get COMPOSE_PROJECT_NAME)
[ -z "$project" ] && project="faoxima"
volume_name="${project}_certs"
mountpoint=$(docker volume inspect --format '{{.Mountpoint}}' "$volume_name" 2>/dev/null)
if [ -n "$mountpoint" ]; then
cert_path="${mountpoint}/live/${domain}/cert.pem"
if [ -f "$cert_path" ]; then
openssl x509 -enddate -noout -in "$cert_path" 2>/dev/null | cut -d= -f2 | tr -d '\r'
fi
return
fi
dc run --rm --no-deps --entrypoint sh certbot -c \
"test -f /etc/letsencrypt/live/${domain}/cert.pem && openssl x509 -enddate -noout -in /etc/letsencrypt/live/${domain}/cert.pem" \
2>/dev/null | cut -d= -f2 | tr -d '\r'
}
ensure_envsubst() {
command -v envsubst >/dev/null 2>&1 && return 0
local output
if ! output=$(apt-get install -y gettext-base 2>&1); then
ui_err "Failed to install gettext-base (needed for envsubst)."
printf '%s\n' "$output"
return 1
fi
if ! command -v envsubst >/dev/null 2>&1; then
ui_err "gettext-base installed but the envsubst binary still isn't on PATH."
return 1
fi
}
render_vhost() {
local domain outfile="$2" pma_allowed_ips ip
domain=$(normalize_domain "$1")
validate_domain_format "$domain" || { ui_err "$DOMAIN_VALIDATION_ERROR"; return 1; }
ensure_envsubst || { ui_err "envsubst is not available and could not be installed."; return 1; }
mkdir -p "$(dirname "$outfile")" || { ui_err "Failed to create directory for ${outfile}."; return 1; }
if [ ! -f "$NGINX_TEMPLATE" ]; then
ui_err "Nginx template not found at ${NGINX_TEMPLATE}."
return 1
fi
DOMAIN="$domain" \
envsubst '${DOMAIN}' < "$NGINX_TEMPLATE" > "$outfile" \
|| { ui_err "Failed to render nginx config to ${outfile}."; return 1; }
pma_allowed_ips=$(get_phpmyadmin_allowed_ips)
if [ -n "$pma_allowed_ips" ]; then
while IFS= read -r ip; do
[ -z "$ip" ] && continue
if ! valid_ipv4_or_cidr "$ip"; then
ui_err "Invalid phpMyAdmin allowed IP in ${ENV_FILE}: ${ip}"
return 1
fi
sed -i "/location \/phpmyadmin\//,/^[[:space:]]*}/ { /^[[:space:]]*deny all;/i\ allow ${ip};
}" "$outfile" || { ui_err "Failed to apply phpMyAdmin IP allowlist to ${outfile}."; return 1; }
done <<EOF
$(printf '%s' "$pma_allowed_ips" | tr ',' '\n')
EOF
fi
if ! pma_enabled; then
local pma_tmp
pma_tmp=$(mktemp "${TMPDIR:-/tmp}/faoxima_vhost.XXXXXX") || { ui_err "Failed to create a temporary file for ${outfile}."; return 1; }
awk '
!skip && index($0, "location /phpmyadmin/ {") {
print " location /phpmyadmin/ {"
print " return 404;"
print " }"
skip = 1
next
}
skip && $0 ~ /^[[:space:]]*}[[:space:]]*$/ { skip = 0; next }
!skip { print }
' "$outfile" > "$pma_tmp" && cat "$pma_tmp" > "$outfile" \
|| { rm -f "$pma_tmp"; ui_err "Failed to disable the phpMyAdmin location in ${outfile}."; return 1; }
rm -f "$pma_tmp"
fi
}
render_bot_location() {
local docroot="$1" upstream="$2" outfile="$3" urlpath="$4"
ensure_envsubst || { ui_err "envsubst is not available and could not be installed."; return 1; }
mkdir -p "$(dirname "$outfile")" || { ui_err "Failed to create directory for ${outfile}."; return 1; }
if [ ! -f "$BOT_NGINX_TEMPLATE" ]; then
ui_err "Bot nginx template not found at ${BOT_NGINX_TEMPLATE}."
return 1
fi
DOC_ROOT="$docroot" APP_UPSTREAM="$upstream" URL_PATH="$urlpath" \
envsubst '${DOC_ROOT} ${APP_UPSTREAM} ${URL_PATH}' < "$BOT_NGINX_TEMPLATE" > "$outfile" \
|| { ui_err "Failed to render bot nginx config to ${outfile}."; return 1; }
}
ensure_dummy_cert() {
local domain
domain=$(normalize_domain "$1")
validate_domain_format "$domain" || { ui_err "$DOMAIN_VALIDATION_ERROR"; return 1; }
dc run --rm --no-deps --entrypoint sh certbot -c "
set -e
dir=/etc/letsencrypt/live/${domain}
if [ -f \"\${dir}/fullchain.pem\" ]; then exit 0; fi
mkdir -p \"\${dir}\"
openssl req -x509 -nodes -newkey rsa:2048 -days 1 \
-keyout \"\${dir}/privkey.pem\" \
-out \"\${dir}/fullchain.pem\" \
-subj \"/CN=${domain}\"
"
}
discard_dummy_cert() {
local domain
domain=$(normalize_domain "$1")
dc run --rm --no-deps --entrypoint sh certbot -c "
set -e
renewal_conf=/etc/letsencrypt/renewal/${domain}.conf
if [ -f \"\${renewal_conf}\" ]; then exit 0; fi
rm -rf \"/etc/letsencrypt/live/${domain}\" \"/etc/letsencrypt/archive/${domain}\"
" || { ui_err "Failed to remove the temporary self-signed certificate for ${domain}."; return 1; }
}
issue_certificate() {
local domain
domain=$(normalize_domain "$1")
validate_domain_format "$domain" || { ui_err "$DOMAIN_VALIDATION_ERROR"; return 1; }
if ! domain_resolves "$domain"; then
ui_err "Domain '${domain}' does not resolve in DNS. Certificate issuance was stopped before touching nginx."
return 1
fi
if dc run --rm --entrypoint certbot certbot certonly --webroot -w /var/www/certbot --agree-tos --non-interactive \
-m "admin@${domain}" -d "$domain"; then
dc exec nginx nginx -s reload 2>/dev/null || true
return 0
fi
ui_warn "Certificate issuance via webroot failed for ${domain} — port 80 may be blocked by something other than our own nginx. Retrying by stopping nginx and binding port 80 directly..."
dc stop nginx || { ui_err "Failed to stop nginx for the standalone issuance attempt."; return 1; }
if dc run --rm -p 80:80 --entrypoint certbot certbot certonly --standalone --agree-tos --non-interactive \
-m "admin@${domain}" -d "$domain"; then
dc start nginx && dc exec nginx nginx -s reload 2>/dev/null
return 0
fi
dc start nginx || ui_err "nginx failed to restart after the failed standalone attempt — start it manually with 'docker compose start nginx'."
return 1
}
env_get() {
local key="$1"
[ -f "$ENV_FILE" ] || return 1
grep -E "^${key}=" "$ENV_FILE" | tail -1 | cut -d'=' -f2-
}
env_set() {
local key="$1" value="$2"
if [ "$key" = "DOMAIN" ]; then
value=$(normalize_domain "$value")
validate_domain_format "$value" || { ui_err "$DOMAIN_VALIDATION_ERROR"; return 1; }
fi
if [ ! -f "$ENV_FILE" ]; then
touch "$ENV_FILE" || { ui_err "Failed to create ${ENV_FILE}."; exit 1; }
fi
if grep -qE "^${key}=" "$ENV_FILE"; then
sed -i "s|^${key}=.*|${key}=${value}|" "$ENV_FILE" || { ui_err "Failed to update ${key} in ${ENV_FILE}."; exit 1; }
else
printf '%s=%s\n' "$key" "$value" >> "$ENV_FILE" || { ui_err "Failed to append ${key} to ${ENV_FILE}."; exit 1; }
fi
}
mysql_binlog_query() {
local root_pass output status
root_pass=$(env_get MYSQL_ROOT_PASSWORD 2>/dev/null || true)
if [ -z "$root_pass" ]; then
ui_err "MYSQL_ROOT_PASSWORD is missing from the installation configuration."
return 1
fi
if output=$(dc exec -T -e MYSQL_PWD="$root_pass" db sh -c '
if ! command -v timeout >/dev/null 2>&1; then
echo "The database container is missing the timeout utility." >&2
exit 1
fi
exec timeout -k 5s 30s mysql --connect-timeout=5 --batch --skip-column-names -uroot -e "$1"
' sh "$1" 2>&1); then
printf '%s\n' "$output"
return 0
else
status=$?
[ -z "$output" ] || printf '%s\n' "$output" >&2
case "$status" in
124|137) printf '%s\n' "MySQL did not respond within 30 seconds. A full disk can block MySQL even when the container reports healthy. Free some disk space outside the database, then retry." >&2 ;;
*) [ -n "$output" ] || printf 'MySQL command failed without diagnostic output (exit code %s). Check the database container logs and disk space.\n' "$status" >&2 ;;
esac
return "$status"
fi
}
cleanup_mysql_logs_now() {
local cid volume image override output confirm new_cid new_volume
if [ ! -f "$ENV_FILE" ] || [ ! -f "$COMPOSE_FILE" ]; then
ui_err "No installed database configuration was found."
return 1
fi
cid=$(dc ps -a -q db 2>/dev/null)
if [ -z "$cid" ]; then
ui_err "The database container was not found; cleanup stopped."
return 1
fi
volume=$(docker inspect --format '{{range .Mounts}}{{if eq .Destination "/var/lib/mysql"}}{{if eq .Type "volume"}}{{.Name}}{{end}}{{end}}{{end}}' "$cid" 2>/dev/null)
image=$(docker inspect --format '{{.Image}}' "$cid" 2>/dev/null)
if [[ ! "$volume" =~ ^[A-Za-z0-9][A-Za-z0-9_.-]+$ ]] || [[ ! "$image" =~ ^sha256:[a-f0-9]{64}$ ]]; then
ui_err "The existing database volume or image could not be verified; cleanup stopped."
return 1
fi
ui_warn "This clears MySQL Docker logs and all inactive binary logs, including recent ones."
ui_warn "The shared database container will be recreated; all bots will briefly lose database access."
ui_info "The existing image and database volume (${volume}) will be reused. Database tables are preserved."
ui_warn "Binary log recovery history will be lost. Do not continue if an offline replica or backup needs these logs."
printf ' %s❯%s Clean MySQL binary and Docker logs now? [y/N]: ' "$C_YELLOW" "$C_RESET"
read -r confirm
if [[ "${confirm,,}" != "y" ]]; then
ui_info "Cancelled."
return 0
fi
override=$(mktemp "${TMPDIR:-/tmp}/faoxima_log_cleanup.XXXXXX.yml") || { ui_err "Cannot prepare the database log cleanup configuration."; return 1; }
if ! cat > "$override" <<EOF
services:
db:
image: ${image}
stop_grace_period: 120s
volumes:
- db_data:/var/lib/mysql
logging:
driver: json-file
options:
max-size: "20m"
max-file: "3"
volumes:
db_data:
external: true
name: ${volume}
EOF
then
rm -f "$override"
ui_err "Cannot write the database log cleanup configuration."
return 1
fi
if ! output=$(dc -f "$override" config --quiet 2>&1); then
rm -f "$override"
ui_err "Database cleanup configuration is invalid: ${output}"
return 1
fi
ui_action "Clearing old MySQL Docker logs and enabling log rotation (3 files of 20 MiB)..."
if ! dc -f "$override" up -d --no-deps --no-build --pull never --force-recreate --timeout 120 db; then
rm -f "$override"
ui_err "Database container recreation failed. Check its status and logs before retrying."
return 1
fi
rm -f "$override"
new_cid=$(dc ps -a -q db 2>/dev/null)
new_volume=$(docker inspect --format '{{range .Mounts}}{{if eq .Destination "/var/lib/mysql"}}{{if eq .Type "volume"}}{{.Name}}{{end}}{{end}}{{end}}' "$new_cid" 2>/dev/null)
if [ "$new_volume" != "$volume" ]; then
ui_err "The database volume could not be verified after recreation. Cleanup stopped."
return 1
fi
ui_action "Waiting for MySQL to become healthy..."
if ! wait_for_healthy db 180; then
ui_err "MySQL Docker logs were cleared, but the database did not become healthy."
dc logs --tail=50 db
return 1
fi
ui_ok "Old MySQL Docker logs cleared; log rotation is enabled."
if ! cleanup_mysql_binlogs_now confirmed; then
ui_warn "Docker log cleanup succeeded, but binary log cleanup did not complete."
return 1
fi
}
cleanup_mysql_binlogs_now() {
local logs active_log before_bytes after_bytes output confirm pass
if [ ! -f "$ENV_FILE" ] || [ ! -f "$COMPOSE_FILE" ]; then
ui_err "No installed database configuration was found."
return 1
fi
ui_action "Checking MySQL binary logs..."
if ! logs=$(mysql_binlog_query "SHOW BINARY LOGS;" 2>&1); then
ui_err "Cannot read binary logs: ${logs}"
ui_info "If the disk is completely full, free some build cache first and retry."
return 1
fi
before_bytes=$(printf '%s\n' "$logs" | awk '{total += $2} END {printf "%.0f", total}')
ui_info "Current binary logs: $(printf '%s\n' "$logs" | awk 'NF {n++} END {print n+0}'), total $(awk -v bytes="$before_bytes" 'BEGIN {printf "%.2f MiB", bytes/1048576}')."
ui_info "This affects the shared MySQL server used by all installed bots. Database tables are preserved."
ui_warn "All inactive binary logs will be removed, including recent ones. Their recovery history will be lost."
ui_warn "Do not continue if an offline replica or a backup still needs these logs."
if [ "${1:-}" != "confirmed" ]; then
printf ' %s❯%s Clean binary logs now? [y/N]: ' "$C_YELLOW" "$C_RESET"
read -r confirm
if [[ "${confirm,,}" != "y" ]]; then
ui_info "Cancelled."
return 0
fi
fi
for pass in 1 2; do
active_log=$(printf '%s\n' "$logs" | awk 'NF {name=$1} END {print name}')
if [[ ! "$active_log" =~ ^[A-Za-z0-9_.-]+$ ]]; then
ui_err "MySQL returned an unexpected binary log name; cleanup stopped."
return 1
fi
ui_action "Removing binary logs older than ${active_log}..."
if ! output=$(mysql_binlog_query "PURGE BINARY LOGS TO '${active_log}'; SHOW WARNINGS;" 2>&1); then
ui_err "Binary log cleanup failed: ${output}"
return 1
fi
[ -n "$output" ] && ui_warn "$output"
if [ "$pass" -eq 1 ]; then
ui_action "Rotating the current binary log..."
if ! output=$(mysql_binlog_query "FLUSH BINARY LOGS;" 2>&1); then
ui_warn "Old logs were processed, but the current log could not be rotated: ${output}"
ui_info "Free additional disk space and retry."
return 1
fi
if ! logs=$(mysql_binlog_query "SHOW BINARY LOGS;" 2>&1); then
ui_err "Cannot read binary logs after rotation: ${logs}"
return 1
fi
fi
done
if ! logs=$(mysql_binlog_query "SHOW BINARY LOGS;" 2>&1); then
ui_err "Cleanup commands completed, but the final log size could not be verified: ${logs}"
return 1
fi
after_bytes=$(printf '%s\n' "$logs" | awk '{total += $2} END {printf "%.0f", total}')
ui_ok "Binary log cleanup completed."
ui_info "$(awk -v before="$before_bytes" -v after="$after_bytes" 'BEGIN {saved=before-after; if (saved<0) saved=0; printf "Binary log size reduced by %.2f MiB; remaining %.2f MiB.", saved/1048576, after/1048576}')"
ui_info "The active log and any logs MySQL needs for connected replicas are retained."
}
cleanup_mysql_binlogs() {
local root_pass
root_pass=$(env_get MYSQL_ROOT_PASSWORD 2>/dev/null || true)
[ -z "$root_pass" ] && return 0
dc exec -T db mysql -uroot -p"${root_pass}" \
-e "PURGE BINARY LOGS BEFORE DATE_SUB(NOW(), INTERVAL 7 DAY);" \
>/dev/null 2>&1 || true
}
cache_get() {
local key="$1" max_age="$2"
local file="${CACHE_DIR}/${key}"
[ -f "$file" ] || return 1
local age
age=$(( $(date +%s) - $(stat -c %Y "$file" 2>/dev/null || echo 0) ))
[ "$age" -gt "$max_age" ] && return 1
cat "$file"
}
cache_set() {
local key="$1" value="$2"
mkdir -p "$CACHE_DIR" 2>/dev/null || return 1
printf '%s' "$value" > "${CACHE_DIR}/${key}"
}
prepare_host_apt() {
if ! command -v apt-get >/dev/null 2>&1; then
ui_err "Automatic host preparation requires an apt-based Debian/Ubuntu system."
return 1
fi
ui_action "Refreshing host package indexes..."
local attempt
for attempt in 1 2 3; do
if DEBIAN_FRONTEND=noninteractive apt-get update -o APT::Update::Error-Mode=any; then
break
fi
if [ "$attempt" -eq 3 ]; then
ui_err "apt-get update failed after 3 attempts. Check the server's internet/DNS connection and try again."
return 1
fi
ui_warn "apt-get update failed (attempt ${attempt}/3); retrying in 5 seconds..."
sleep 5
done
ui_action "Upgrading installed host packages..."
DEBIAN_FRONTEND=noninteractive apt-get upgrade -y || {
ui_err "apt-get upgrade failed while preparing the host."
return 1
}
ui_ok "Host package indexes and installed packages are up to date."
}
ensure_host_prerequisites() {
local missing_packages=()
local cmd package
local required_commands=(
curl:curl
wget:wget
unzip:unzip
zip:zip
openssl:openssl
envsubst:gettext-base
ss:iproute2
gpg:gnupg
)
for cmd in "${required_commands[@]}"; do
package="${cmd#*:}"
cmd="${cmd%%:*}"
command -v "$cmd" >/dev/null 2>&1 || missing_packages+=("$package")
done
if [ "${#missing_packages[@]}" -eq 0 ]; then
ui_ok "Required host prerequisites are already installed."
return 0
fi
if ! command -v apt-get >/dev/null 2>&1; then
ui_err "Missing required commands: ${missing_packages[*]}. Automatic prerequisite installation currently requires an apt-based Debian/Ubuntu system."
return 1
fi
local unique_packages=() seen=" " item
for item in "${missing_packages[@]}"; do
if [[ "$seen" != *" $item "* ]]; then
unique_packages+=("$item")
seen+="$item "
fi
done
ui_action "Installing missing prerequisites automatically: ${unique_packages[*]}"
DEBIAN_FRONTEND=noninteractive apt-get update || { ui_err "apt-get update failed while installing prerequisites."; return 1; }