forked from mahdiMGF2/mirzabot
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathinstall.sh
More file actions
2165 lines (2024 loc) · 97.9 KB
/
Copy pathinstall.sh
File metadata and controls
2165 lines (2024 loc) · 97.9 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
# Checking Root Access
if [[ $EUID -ne 0 ]]; then
echo -e "\033[31m[ERROR]\033[0m Please run this script as \033[1mroot\033[0m."
exit 1
fi
INSTALL_LOG="/tmp/mirza_install.log"
export DEBIAN_FRONTEND=noninteractive
export NEEDRESTART_MODE=a
export NEEDRESTART_SUSPEND=1
export APT_LISTCHANGES_FRONTEND=none
# ── Progress / ETA state ─────────────────────────────────────
ETA_REMAINING=0 # estimated seconds left for the whole install
STEP_NO=0 # how many steps have started
STEP_TOTAL=0 # total steps planned for this run (0 = unknown)
# Seconds -> "9s" or "2m05s"
_fmt_secs() {
local s=$1
[ "$s" -lt 0 ] && s=0
if [ "$s" -lt 60 ]; then printf '%ds' "$s"; else printf '%dm%02ds' $((s / 60)) $((s % 60)); fi
}
# Filled/empty bar of WIDTH chars at PCT percent
_bar() {
local pct=$1 width=${2:-14} filled i out=""
[ "$pct" -gt 100 ] && pct=100; [ "$pct" -lt 0 ] && pct=0
filled=$(( pct * width / 100 ))
for ((i = 0; i < width; i++)); do
if [ "$i" -lt "$filled" ]; then out+="█"; else out+="░"; fi
done
printf '%s' "$out"
}
# Expected duration (seconds) for a step, matched by its label.
# Keeps the per-step bar and the overall ETA in sync.
_step_eta() {
case "$1" in
"Preparing package manager"*) echo 5 ;;
"Adding PHP repository"*|"Retrying PHP repository"*) echo 15 ;;
"Updating & upgrading"*|"Re-running system update"*) echo 120 ;;
"Installing base tools"*) echo 25 ;;
"Installing PHP 8.2"*) echo 30 ;;
"Installing web stack"*) echo 90 ;;
"Repairing broken MySQL"*) echo 90 ;;
"Re-installing web stack"*) echo 90 ;;
"Installing phpMyAdmin"*) echo 40 ;;
"Installing extra modules"*) echo 25 ;;
"Enabling & starting services"*) echo 8 ;;
"Configuring firewall"*) echo 15 ;;
"Restarting Apache"*) echo 5 ;;
"Setting PHP 8.2 as the active"*) echo 6 ;;
"Downloading Mirza"*) echo 20 ;;
"Extracting source files"*) echo 5 ;;
"Configuring MySQL root access"*) echo 10 ;;
"Opening firewall ports"*) echo 4 ;;
"Stopping Apache"*) echo 4 ;;
"Installing Let's Encrypt"*|"Installing certbot"*) echo 25 ;;
"Requesting SSL certificate"*) echo 25 ;;
"Installing Apache certbot plugin"*) echo 25 ;;
"Configuring SSL on Apache"*) echo 20 ;;
"Enabling & starting Apache"*|"Starting Apache"*) echo 5 ;;
"Configuring Apache virtual hosts"*) echo 6 ;;
"Creating database & user"*) echo 5 ;;
"Setting Telegram webhook"*) echo 5 ;;
"Initializing database tables"*) echo 15 ;;
*) echo 8 ;;
esac
}
# Plan the run: count pending steps + total expected time (skips done phases).
plan_eta() {
STEP_TOTAL=0; ETA_REMAINING=0; STEP_NO=0
phase_done DEPS || { STEP_TOTAL=$((STEP_TOTAL + 12)); ETA_REMAINING=$((ETA_REMAINING + 388)); }
phase_done FILES || { STEP_TOTAL=$((STEP_TOTAL + 2)); ETA_REMAINING=$((ETA_REMAINING + 25)); }
phase_done DBROOT || { STEP_TOTAL=$((STEP_TOTAL + 1)); ETA_REMAINING=$((ETA_REMAINING + 10)); }
if ! phase_done SSL; then
if [ -f "/etc/letsencrypt/live/$(state_get DOMAIN)/fullchain.pem" ]; then
STEP_TOTAL=$((STEP_TOTAL + 1)); ETA_REMAINING=$((ETA_REMAINING + 5))
else
STEP_TOTAL=$((STEP_TOTAL + 7)); ETA_REMAINING=$((ETA_REMAINING + 108))
fi
fi
phase_done VHOST || { STEP_TOTAL=$((STEP_TOTAL + 1)); ETA_REMAINING=$((ETA_REMAINING + 6)); }
phase_done DB || { STEP_TOTAL=$((STEP_TOTAL + 1)); ETA_REMAINING=$((ETA_REMAINING + 5)); }
phase_done WEBHOOK || { STEP_TOTAL=$((STEP_TOTAL + 3)); ETA_REMAINING=$((ETA_REMAINING + 25)); }
}
print_header() {
echo ""
echo -e "\033[1;34m╭────────────────────────────────────────────────╮\033[0m"
printf "\033[1;34m│\033[0m \033[1;36m%-46s\033[0m \033[1;34m│\033[0m\n" "$1"
echo -e "\033[1;34m╰────────────────────────────────────────────────╯\033[0m"
}
run_step() {
local msg="$1"
local cmd="$2"
local eta="${3:-$(_step_eta "$msg")}"
[ "$eta" -lt 1 ] && eta=1
STEP_NO=$((STEP_NO + 1))
local counter="$STEP_NO"
[ "$STEP_TOTAL" -gt 0 ] && counter="$STEP_NO/$STEP_TOTAL"
: > "$INSTALL_LOG"
local start; start=$(date +%s)
bash -c "$cmd" >> "$INSTALL_LOG" 2>&1 &
local pid=$!
local frames=("⠋" "⠙" "⠹" "⠸" "⠼" "⠴" "⠦" "⠧" "⠇" "⠏")
local n=${#frames[@]}
local i=0
tput civis 2>/dev/null
while kill -0 "$pid" 2>/dev/null; do
local el=$(( $(date +%s) - start ))
local pct=$(( el * 100 / eta ))
[ "$pct" -gt 95 ] && pct=95 # don't show full until it really finishes
local left=$(( eta - el )) lefttxt
if [ "$left" -gt 0 ]; then lefttxt="~$(_fmt_secs $left) left"; else lefttxt="finishing…"; fi
local otxt=""
if [ "$ETA_REMAINING" -gt 0 ]; then
local orem=$(( ETA_REMAINING - el )); [ "$orem" -lt 0 ] && orem=0
otxt=" \033[0;37m· total ~$(_fmt_secs $orem)\033[0m"
fi
printf "\r\033[K \033[1;33m%s\033[0m \033[0;37m[%s]\033[0m %s \033[1;36m▕%s▏\033[0m \033[0;37m%s · %s\033[0m%b" \
"${frames[$i]}" "$counter" "$msg" "$(_bar "$pct" 14)" "$(_fmt_secs $el)" "$lefttxt" "$otxt"
i=$(( (i + 1) % n ))
sleep 0.2
done
wait "$pid"
local rc=$?
local el=$(( $(date +%s) - start ))
tput cnorm 2>/dev/null
if [ "$ETA_REMAINING" -gt 0 ]; then
ETA_REMAINING=$(( ETA_REMAINING - eta )); [ "$ETA_REMAINING" -lt 0 ] && ETA_REMAINING=0
fi
if [ "$rc" -eq 0 ]; then
printf "\r\033[K \033[1;32m✔\033[0m \033[0;37m[%s]\033[0m %s \033[0;37m(%s)\033[0m\n" "$counter" "$msg" "$(_fmt_secs $el)"
else
printf "\r\033[K \033[1;31m✘\033[0m \033[0;37m[%s]\033[0m %s \033[0;37m(%s)\033[0m\n" "$counter" "$msg" "$(_fmt_secs $el)"
fi
return "$rc"
}
show_step_error() {
echo -e "\033[1;31m──────────────── Error details ─────────────────\033[0m"
tail -n 20 "$INSTALL_LOG" 2>/dev/null
echo -e "\033[1;31m─────────────────────────────────────────────────\033[0m"
}
# ── Menu UI helpers ──────────────────────────────────────────
C_BORDER=$'\033[1;36m'; C_TITLE=$'\033[1;37m'; C_DIM=$'\033[0;37m'
C_KEY=$'\033[1;33m'; C_TXT=$'\033[0;37m'; C_OK=$'\033[1;32m'
C_BAD=$'\033[1;31m'; C_WARN=$'\033[1;33m'; C_PROMPT=$'\033[1;36m'
CR=$'\033[0m'
UI_W=52 # width of horizontal rules (no right border = never misaligns)
_repeat() { local ch="$1" n="$2" out="" i; for ((i=0;i<n;i++)); do out+="$ch"; done; printf '%s' "$out"; }
# Horizontal rules (left-aligned, no right edge to drift)
_rule() { printf " ${C_BORDER}%s${CR}\n" "$(_repeat "─" "$UI_W")"; }
_drule() { printf " ${C_BORDER}%s${CR}\n" "$(_repeat "━" "$UI_W")"; }
# Banner: rules + left-aligned title (no full box)
banner() {
echo
_drule
printf " ${C_OK}▌${CR} ${C_TITLE}MIRZA${CR} ${C_DIM}— VPN Subscription Management${CR}\n"
_drule
}
# Menu item row: [n] label (left-aligned, no right border)
_mi() { printf " ${C_KEY}[%s]${CR} ${C_TXT}%b${CR}\n" "$1" "$2"; }
# ── DNS auto-fix (used early, before any download) ───────────
RESOLV="/etc/resolv.conf"
DNS_SERVERS=("1.1.1.1" "8.8.8.8" "9.9.9.9")
dns_works() {
getent hosts github.com >/dev/null 2>&1 && return 0
getent hosts api.telegram.org >/dev/null 2>&1 && return 0
return 1
}
ensure_dns() {
dns_works && return 0
echo -e " ${C_WARN}!${CR} ${C_WARN}DNS resolution failed - configuring public DNS...${CR}"
if [ -L "$RESOLV" ]; then
rm -f "$RESOLV" 2>/dev/null
elif [ -f "$RESOLV" ] && [ ! -f "${RESOLV}.mirza.bak" ]; then
cp -a "$RESOLV" "${RESOLV}.mirza.bak" 2>/dev/null
fi
{ local d; for d in "${DNS_SERVERS[@]}"; do echo "nameserver $d"; done; } > "$RESOLV" 2>/dev/null
if command -v resolvectl >/dev/null 2>&1; then
local ifc; ifc=$(ip route show default 2>/dev/null | awk '/default/{print $5; exit}')
[ -n "$ifc" ] && resolvectl dns "$ifc" "${DNS_SERVERS[@]}" 2>/dev/null || true
fi
sleep 1
dns_works && { echo -e " ${C_OK}●${CR} ${C_OK}DNS is now working.${CR}"; return 0; }
echo -e " ${C_BAD}●${CR} ${C_BAD}DNS still failing after applying public resolvers.${CR}"
return 1
}
# Ensure /usr/local/bin/mirza points at the master script
_link_mirza() {
local master="$1" link="$2"
chmod +x "$master" 2>/dev/null
if [ ! -e "$link" ] || [ "$(readlink -f "$link" 2>/dev/null)" != "$(readlink -f "$master" 2>/dev/null)" ]; then
ln -sf "$master" "$link"
fi
chmod +x "$link" 2>/dev/null
}
# Self-update: every run, fetch the latest script from GitHub, validate it,
# install it to /root/install.sh, link it into /usr/local/bin, and re-exec.
function self_update_script() {
local MASTER_PATH="/root/install.sh"
local BIN_LINK="/usr/local/bin/mirza"
local URL="https://raw.githubusercontent.com/mahdiMGF2/mirzabot/main/install.sh"
local TEMP_FILE="/tmp/mirzabot_update.sh"
# Make sure DNS works before reaching GitHub
ensure_dns >/dev/null 2>&1
echo -e "\e[33mChecking for the latest script version...\033[0m"
rm -f "$TEMP_FILE"
curl -fsSL --max-time 15 -o "$TEMP_FILE" "$URL" 2>/dev/null \
|| wget -q -O "$TEMP_FILE" "$URL" 2>/dev/null
# Normalize line endings so a CRLF download can never break bash
[ -f "$TEMP_FILE" ] && sed -i 's/\r$//' "$TEMP_FILE"
# Validate the download is a complete, valid bash script (not a 404/HTML/partial)
local valid=0
if [ -s "$TEMP_FILE" ] \
&& head -n1 "$TEMP_FILE" | grep -q '^#!/bin/bash' \
&& grep -q 'process_arguments' "$TEMP_FILE" \
&& bash -n "$TEMP_FILE" 2>/dev/null; then
valid=1
fi
if [ "$valid" -ne 1 ]; then
echo -e "\e[91mWarning: could not fetch a valid update (offline / bad download). Using current version.\033[0m"
rm -f "$TEMP_FILE"
if [ ! -f "$MASTER_PATH" ]; then
echo -e "\e[91mCritical: cannot install the script for the first time without internet.\033[0m"
exit 1
fi
_link_mirza "$MASTER_PATH" "$BIN_LINK"
return 0
fi
local LOCAL_HASH REMOTE_HASH
if [ -f "$MASTER_PATH" ]; then
LOCAL_HASH=$(md5sum "$MASTER_PATH" | awk '{print $1}')
else
LOCAL_HASH="not_installed"
fi
REMOTE_HASH=$(md5sum "$TEMP_FILE" | awk '{print $1}')
if [ "$LOCAL_HASH" != "$REMOTE_HASH" ]; then
if [ "$LOCAL_HASH" = "not_installed" ]; then
echo -e "\e[32mInstalling script to the system...\033[0m"
else
echo -e "\e[32mNew version found - updating...\033[0m"
fi
install -m 0755 "$TEMP_FILE" "$MASTER_PATH" 2>/dev/null || { mv "$TEMP_FILE" "$MASTER_PATH"; chmod +x "$MASTER_PATH"; }
rm -f "$TEMP_FILE"
_link_mirza "$MASTER_PATH" "$BIN_LINK"
echo -e "\e[32mUpdated. Restarting with the latest version...\033[0m"
sleep 1
exec bash "$MASTER_PATH" "$@"
fi
# Already up to date - just make sure it is linked under /usr/local/bin
rm -f "$TEMP_FILE"
_link_mirza "$MASTER_PATH" "$BIN_LINK"
echo -e "\e[32mScript is up to date.\033[0m"
}
self_update_script "$@"
# ── Repo / paths ─────────────────────────────────────────────
BOT_DIR_DEFAULT="/var/www/html/mirzaprobotconfig"
CONFIG_FILE_DEFAULT="$BOT_DIR_DEFAULT/config.php"
GIT_REPO="mahdiMGF2/mirzabot"
LATEST_CACHE="/tmp/.mirza_latest_version"
IP_CACHE="/tmp/.mirza_server_ip"
# ── Resumable-install state engine ───────────────────────────
# Survives reboots / network drops. Lets a failed install resume
# from the last completed phase instead of starting from scratch.
STATE_DIR="/root/confmirza"
STATE_FILE="$STATE_DIR/.mirza_install_state"
state_init() {
mkdir -p "$STATE_DIR" 2>/dev/null
if [ ! -f "$STATE_FILE" ]; then
: > "$STATE_FILE"
chmod 600 "$STATE_FILE" 2>/dev/null
fi
}
# state_set KEY VALUE -> store a persistent answer (domain/token/etc.)
state_set() {
state_init
sed -i "/^$1=/d" "$STATE_FILE" 2>/dev/null
printf '%s=%s\n' "$1" "$2" >> "$STATE_FILE"
}
# state_get KEY -> echo the stored value (empty if missing)
state_get() {
[ -f "$STATE_FILE" ] || return 0
grep -E "^$1=" "$STATE_FILE" 2>/dev/null | tail -1 | cut -d= -f2-
}
# phase_done NAME -> 0 if the phase already completed successfully
phase_done() {
[ -f "$STATE_FILE" ] && grep -qxF "PHASE:$1" "$STATE_FILE" 2>/dev/null
}
# mark_phase NAME -> record a phase as completed
mark_phase() {
state_init
grep -qxF "PHASE:$1" "$STATE_FILE" 2>/dev/null || echo "PHASE:$1" >> "$STATE_FILE"
}
# has_resumable_state -> 0 if an unfinished install is on disk
has_resumable_state() {
[ -f "$STATE_FILE" ] || return 1
{ grep -q '^PHASE:' "$STATE_FILE" 2>/dev/null || grep -q '^STARTED=' "$STATE_FILE" 2>/dev/null; } \
&& ! phase_done COMPLETE
}
state_clear() { rm -f "$STATE_FILE" 2>/dev/null; }
# ── apt/dpkg recovery ────────────────────────────────────────
# A previous interrupted apt run (or Ubuntu's background
# unattended-upgrades) can hold the dpkg lock, making the next
# apt command hang forever. This waits for any LIVE apt to finish,
# clears locks left by a DEAD process, then repairs dpkg state.
apt_recover() {
local i=0
# 1) If a real apt/dpkg is running (e.g. unattended-upgrades), wait for it
if pgrep -x 'apt|apt-get|dpkg|unattended-upgr' >/dev/null 2>&1; then
echo "Another apt/dpkg process is running; waiting up to 3 minutes for it to finish..."
while pgrep -x 'apt|apt-get|dpkg|unattended-upgr' >/dev/null 2>&1; do
sleep 3; i=$((i + 1)); [ "$i" -ge 60 ] && break
done
fi
# 2) Disable Ubuntu auto-update timers during install so they cannot re-grab the lock
systemctl stop apt-daily.service apt-daily-upgrade.service \
unattended-upgrades.service >/dev/null 2>&1
systemctl stop apt-daily.timer apt-daily-upgrade.timer >/dev/null 2>&1
# 3) No live holder now -> remove stale locks left by the crashed run
if ! pgrep -x 'apt|apt-get|dpkg|unattended-upgr' >/dev/null 2>&1; then
rm -f /var/lib/apt/lists/lock /var/cache/apt/archives/lock \
/var/lib/dpkg/lock /var/lib/dpkg/lock-frontend 2>/dev/null
fi
# 4) Repair any half-configured packages from the interruption
DEBIAN_FRONTEND=noninteractive dpkg --configure -a >/dev/null 2>&1
return 0
}
export -f apt_recover
# Configure MySQL root login (all output captured by run_step's log).
setup_mysql_root() {
sudo mkdir -p /root/confmirza || return 1
touch /root/confmirza/dbrootmirza.txt || return 1
sudo chmod -R 777 /root/confmirza/dbrootmirza.txt || return 1
local randomdbpasstxt passs userrr RANDOM_NUMBER
randomdbpasstxt=$(openssl rand -base64 10 | tr -dc 'a-zA-Z0-9' | cut -c1-8)
RANDOM_NUMBER=$(openssl rand -base64 12 | tr -dc 'a-zA-Z0-9' | cut -c1-12)
echo "\$user = 'root';" >> /root/confmirza/dbrootmirza.txt
echo "\$pass = '${randomdbpasstxt}';" >> /root/confmirza/dbrootmirza.txt
echo "\$path = '${RANDOM_NUMBER}';" >> /root/confmirza/dbrootmirza.txt
passs=$(grep '$pass' /root/confmirza/dbrootmirza.txt | cut -d"'" -f2)
userrr=$(grep '$user' /root/confmirza/dbrootmirza.txt | cut -d"'" -f2)
if ! sudo mysql -u "$userrr" -p"$passs" -e "alter user '$userrr'@'localhost' identified with mysql_native_password by '$passs';FLUSH PRIVILEGES;"; then
# Recovery via skip-grant-tables
sudo sed -i '$ a skip-grant-tables' /etc/mysql/mysql.conf.d/mysqld.cnf
sudo systemctl restart mysql
sudo mysql <<EOF
DROP USER IF EXISTS 'root'@'localhost';
CREATE USER 'root'@'localhost' IDENTIFIED BY '${passs}';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION;
FLUSH PRIVILEGES;
EOF
sudo sed -i '/skip-grant-tables/d' /etc/mysql/mysql.conf.d/mysqld.cnf
sudo systemctl restart mysql
echo "SELECT 1" | mysql -u"$userrr" -p"$passs" 2>/dev/null || return 1
fi
return 0
}
export -f setup_mysql_root
# True if a package is installed and configured.
_pkg_installed() { dpkg-query -W -f='${Status}' "$1" 2>/dev/null | grep -q 'install ok installed'; }
# Refuse to install on a server that already has conflicting software.
# Only runs on a brand-new install (never on resume / Mirza's own partial state).
precheck_fresh_server() {
local found=()
_pkg_installed apache2 && found+=("apache2 (web server)")
{ _pkg_installed nginx || _pkg_installed nginx-core || _pkg_installed nginx-full; } && found+=("nginx (web server)")
{ _pkg_installed mysql-server || _pkg_installed mysql-server-8.0; } && found+=("mysql-server")
{ _pkg_installed mariadb-server || _pkg_installed mariadb-server-10.6; } && found+=("mariadb-server")
_pkg_installed phpmyadmin && found+=("phpMyAdmin")
# Known VPN panels
{ [ -d /opt/marzban ] || [ -d /var/lib/marzban ]; } && found+=("Marzban panel")
{ [ -d /etc/x-ui ] || [ -d /usr/local/x-ui ]; } && found+=("x-ui / 3x-ui panel")
{ [ -d /opt/hiddify-manager ] || [ -d /opt/hiddify-config ]; } && found+=("Hiddify panel")
if [ ${#found[@]} -gt 0 ]; then
clear
banner
_sec "Server is not clean"
printf " ${C_BAD}●${CR} ${C_BAD}This installer needs a fresh server with no other software installed.${CR}\n"
printf " ${C_DIM}Detected conflicting components:${CR}\n"
local f
for f in "${found[@]}"; do printf " ${C_WARN}-${CR} ${C_TXT}%s${CR}\n" "$f"; done
echo ""
printf " ${C_TXT}Use a clean Ubuntu 22.04/24.04 server (no web server, database, or panel)${CR}\n"
printf " ${C_TXT}or reinstall the OS, then run the installer again.${CR}\n"
return 1
fi
return 0
}
# Repair a broken / half-configured MySQL left by an interrupted apt run.
# Safe to wipe data here: this only runs during a fresh install, before any
# Mirza database is created (the fresh-server precheck guarantees no real DB).
repair_mysql() {
export DEBIAN_FRONTEND=noninteractive
systemctl stop mysql 2>/dev/null
# 1) Gentle fix first
dpkg --configure -a >/dev/null 2>&1
apt-get install -f -y >/dev/null 2>&1
if dpkg-query -W -f='${Status}' mysql-server-8.0 2>/dev/null | grep -q 'install ok installed'; then
return 0
fi
# 2) Hard reset: purge MySQL and wipe its (empty) data dir, then reinstall fresh
apt-get purge -y 'mysql-server*' 'mysql-client*' 'mysql-community*' mysql-common >/dev/null 2>&1
apt-get autoremove -y >/dev/null 2>&1
rm -rf /var/lib/mysql /var/log/mysql /etc/mysql
dpkg --configure -a >/dev/null 2>&1
apt-get update >/dev/null 2>&1
return 0
}
export -f repair_mysql
# install_pause "<where>" -> save progress and exit WITHOUT rolling back.
# Re-running `mirza install` will pick up from the last completed phase.
install_pause() {
local where="$1"
echo ""
echo -e " ${C_WARN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${CR}"
echo -e " ${C_WARN}● Installation paused${CR} ${C_DIM}(${where})${CR}"
echo -e " ${C_DIM}This is usually caused by the server losing internet or a network error.${CR}"
echo ""
echo -e " ${C_TXT}Completed steps are saved. Just run it again:${CR}"
echo -e " ${C_KEY}mirza install${CR}"
echo -e " ${C_DIM}It resumes from this step; values you already entered (domain/token/...) will not be asked again.${CR}"
echo -e " ${C_WARN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${CR}"
echo ""
exit 1
}
# Colored status dot
_dot() {
case "$1" in
ok) printf "${C_OK}●${CR}" ;;
bad) printf "${C_BAD}●${CR}" ;;
warn) printf "${C_WARN}●${CR}";;
*) printf "${C_DIM}●${CR}" ;;
esac
}
# Dashboard section header + key/value row helpers
_sec() { printf "\n ${C_KEY}▌${CR} ${C_TITLE}%s${CR}\n" "$1"; _rule; }
_kv() { printf " ${C_DIM}%-11s${CR}${C_BORDER}:${CR} %b${CR}\n" "$1" "$2"; }
# Read the installed version from the source 'version' file
get_installed_version() {
if [ -f "$BOT_DIR_DEFAULT/version" ]; then
tr -d ' \t\r\n' < "$BOT_DIR_DEFAULT/version"
else
echo ""
fi
}
# Get latest version (newest git tag) from GitHub, cached for 1 hour
get_latest_version() {
if [ -f "$LATEST_CACHE" ] && [ $(( $(date +%s) - $(stat -c %Y "$LATEST_CACHE" 2>/dev/null || echo 0) )) -lt 3600 ]; then
cat "$LATEST_CACHE"
return
fi
local tags v
tags=$(curl -fsSL --max-time 6 "https://api.github.com/repos/${GIT_REPO}/tags" 2>/dev/null)
if [ -n "$tags" ]; then
if command -v jq >/dev/null 2>&1; then
v=$(echo "$tags" | jq -r '.[].name' 2>/dev/null | sort -V | tail -1)
else
v=$(echo "$tags" | grep -oE '"name"[[:space:]]*:[[:space:]]*"[^"]+"' | sed -E 's/.*"([^"]+)".*/\1/' | sort -V | tail -1)
fi
fi
if [ -n "$v" ]; then
echo "$v" > "$LATEST_CACHE"
echo "$v"
fi
}
# Print all release tags, newest first (one per line)
list_tags_desc() {
local tags
tags=$(curl -fsSL --max-time 8 "https://api.github.com/repos/${GIT_REPO}/tags" 2>/dev/null)
[ -z "$tags" ] && return 1
if command -v jq >/dev/null 2>&1; then
echo "$tags" | jq -r '.[].name' 2>/dev/null | sort -Vr
else
echo "$tags" | grep -oE '"name"[[:space:]]*:[[:space:]]*"[^"]+"' | sed -E 's/.*"([^"]+)".*/\1/' | sort -Vr
fi
}
# Choose which source to download.
# Sets globals: SRC_ZIP_URL, SRC_LABEL
# Honors flags ARG_CHANNEL (beta|release|auto) and ARG_VERSION (tag) for non-interactive use.
# Returns: 0 = chosen, 1 = error, 2 = back to menu
choose_source() {
SRC_ZIP_URL=""; SRC_LABEL=""
local beta="https://github.com/${GIT_REPO}/archive/refs/heads/main.zip"
local tagbase="https://github.com/${GIT_REPO}/archive/refs/tags"
# ── Non-interactive (flags) ──────────────────────────────
if [ -n "$ARG_VERSION" ]; then
# Verify the requested tag actually exists (when the list is reachable)
local _avail; _avail=$(list_tags_desc)
if [ -n "$_avail" ] && ! echo "$_avail" | grep -qx "$ARG_VERSION"; then
echo -e " ${C_BAD}●${CR} ${C_BAD}Version '${ARG_VERSION}' not found.${CR}"
echo -e " ${C_DIM}Available:${CR} $(echo "$_avail" | tr '\n' ' ')"
return 1
fi
SRC_ZIP_URL="${tagbase}/${ARG_VERSION}.zip"; SRC_LABEL="Release ${ARG_VERSION}"; return 0
fi
if [ -n "$ARG_CHANNEL" ]; then
case "$ARG_CHANNEL" in
beta|main) SRC_ZIP_URL="$beta"; SRC_LABEL="Beta (main)"; return 0 ;;
release|auto|latest|stable)
local l; l=$(get_latest_version)
if [ -n "$l" ]; then SRC_ZIP_URL="${tagbase}/${l}.zip"; SRC_LABEL="Release ${l}";
else SRC_ZIP_URL="$beta"; SRC_LABEL="Beta (main)"; fi
return 0 ;;
*) echo -e " ${C_BAD}Unknown channel: ${ARG_CHANNEL}${CR}"; return 1 ;;
esac
fi
# ── Interactive ──────────────────────────────────────────
_sec "Select version"
_mi "1" "Automatic ${C_DIM}(latest stable release)${CR}"
_mi "2" "Choose a specific release version"
_mi "3" "Beta ${C_DIM}(latest main branch - may be unstable)${CR}"
_mi "0" "Back to menu"
echo ""
printf " ${C_PROMPT}❯${CR} Select ${C_DIM}[0-3]${CR}: "
local S; read -r S
case "$S" in
0) return 2 ;;
1)
local l; l=$(get_latest_version)
if [ -n "$l" ]; then SRC_ZIP_URL="${tagbase}/${l}.zip"; SRC_LABEL="Release ${l}";
else
echo -e " ${C_WARN}Could not detect latest release; falling back to Beta.${CR}"
SRC_ZIP_URL="$beta"; SRC_LABEL="Beta (main)"
fi
return 0 ;;
2)
echo ""
echo -e " ${C_DIM}Fetching available versions...${CR}"
local TAGS=(); mapfile -t TAGS < <(list_tags_desc)
if [ "${#TAGS[@]}" -eq 0 ]; then
echo -e " ${C_BAD}●${CR} ${C_BAD}Could not fetch release list (offline or rate-limited).${CR}"
return 1
fi
_sec "Available versions"
local i=1 t
for t in "${TAGS[@]}"; do
if [ "$i" -eq 1 ]; then _mi "$i" "${t} ${C_OK}(latest)${CR}"; else _mi "$i" "$t"; fi
i=$((i+1))
done
_mi "0" "Back to menu"
echo ""
printf " ${C_PROMPT}❯${CR} Select version ${C_DIM}[default: 1]${CR}: "
local V; read -r V; [ -z "$V" ] && V=1
[ "$V" = "0" ] && return 2
if ! [[ "$V" =~ ^[0-9]+$ ]] || [ "$V" -lt 1 ] || [ "$V" -gt "${#TAGS[@]}" ]; then
echo -e " ${C_BAD}Invalid selection.${CR}"; return 1
fi
local c="${TAGS[$((V-1))]}"
SRC_ZIP_URL="${tagbase}/${c}.zip"; SRC_LABEL="Release ${c}"
return 0 ;;
3) SRC_ZIP_URL="$beta"; SRC_LABEL="Beta (main)"; return 0 ;;
*) echo -e " ${C_BAD}Invalid selection.${CR}"; return 1 ;;
esac
}
# Get public server IP, cached for 1 hour (falls back to local IP)
get_server_ip() {
if [ -f "$IP_CACHE" ] && [ $(( $(date +%s) - $(stat -c %Y "$IP_CACHE" 2>/dev/null || echo 0) )) -lt 3600 ]; then
cat "$IP_CACHE"
return
fi
local ip
ip=$(curl -fsSL --max-time 4 ifconfig.me 2>/dev/null)
[ -z "$ip" ] && ip=$(curl -fsSL --max-time 4 https://api.ipify.org 2>/dev/null)
[ -z "$ip" ] && ip=$(hostname -I 2>/dev/null | awk '{print $1}')
[ -z "$ip" ] && ip="n/a"
echo "$ip" > "$IP_CACHE"
echo "$ip"
}
# ── Dashboard sections ───────────────────────────────────────
version_section() {
local inst latest
inst=$(get_installed_version)
latest=$(get_latest_version)
_sec "Version"
if [ -n "$inst" ]; then
_kv "Installed" "$(_dot ok) ${C_OK}${inst}${CR}"
else
_kv "Installed" "$(_dot bad) ${C_BAD}not installed${CR}"
fi
if [ -n "$latest" ]; then
if [ -n "$inst" ] && [ "$inst" = "$latest" ]; then
_kv "Latest" "$(_dot ok) ${C_OK}${latest}${CR} ${C_DIM}(up to date)${CR}"
elif [ -n "$inst" ]; then
_kv "Latest" "$(_dot warn) ${C_WARN}${latest}${CR} ${C_WARN}(update available!)${CR}"
else
_kv "Latest" "$(_dot warn) ${C_DIM}${latest}${CR}"
fi
else
_kv "Latest" "$(_dot warn) ${C_DIM}unknown (offline)${CR}"
fi
_kv "Channel" "${C_DIM}t.me/mirzapanel${CR}"
_kv "Group" "${C_DIM}t.me/mirzapanelgroup${CR}"
}
bot_section() {
SSL_DOMAIN=""
_sec "Bot Status"
if [ ! -f "$CONFIG_FILE_DEFAULT" ]; then
_kv "State" "$(_dot bad) ${C_BAD}not installed${CR}"
return
fi
_kv "State" "$(_dot ok) ${C_OK}installed${CR}"
SSL_DOMAIN=$(grep '^\$domainhosts' "$CONFIG_FILE_DEFAULT" | cut -d"'" -f2 | cut -d'/' -f1)
if [ -n "$SSL_DOMAIN" ] && [ -f "/etc/letsencrypt/live/$SSL_DOMAIN/cert.pem" ]; then
local expiry days
expiry=$(openssl x509 -enddate -noout -in "/etc/letsencrypt/live/$SSL_DOMAIN/cert.pem" 2>/dev/null | cut -d= -f2)
days=$(( ( $(date -d "$expiry" +%s 2>/dev/null || echo 0) - $(date +%s) ) / 86400 ))
if [ "$days" -gt 14 ]; then
_kv "SSL" "$(_dot ok) ${C_OK}valid${CR} ${C_DIM}(${days} days left)${CR}"
elif [ "$days" -gt 0 ]; then
_kv "SSL" "$(_dot warn) ${C_WARN}valid${CR} ${C_DIM}(${days} days left - renew soon)${CR}"
else
_kv "SSL" "$(_dot bad) ${C_BAD}expired${CR}"
fi
else
_kv "SSL" "$(_dot warn) ${C_WARN}certificate not found${CR}"
fi
if [ -n "$SSL_DOMAIN" ]; then
_kv "Domain" "${C_DIM}https://${SSL_DOMAIN}${CR}"
_kv "phpMyAdmin" "${C_DIM}https://${SSL_DOMAIN}/phpmyadmin${CR}"
fi
}
# Read the Telegram webhook using the bot token from config.php.
# Prints webhook URL / pending count, and surfaces any error message.
webhook_section() {
_sec "Webhook"
if [ ! -f "$CONFIG_FILE_DEFAULT" ]; then
_kv "Status" "$(_dot warn) ${C_DIM}n/a (bot not installed)${CR}"
return
fi
local token info ok url pending err errdate apierr when
token=$(grep '^\$APIKEY' "$CONFIG_FILE_DEFAULT" | cut -d"'" -f2)
if [ -z "$token" ]; then
_kv "Status" "$(_dot bad) ${C_BAD}token not found in config.php${CR}"
return
fi
info=$(curl -fsSL --max-time 8 "https://api.telegram.org/bot${token}/getWebhookInfo" 2>/dev/null)
if [ -z "$info" ]; then
_kv "Status" "$(_dot bad) ${C_BAD}cannot reach Telegram API${CR}"
printf " ${C_BAD}Error:${CR} request to api.telegram.org failed (network/timeout).\n"
return
fi
if command -v jq >/dev/null 2>&1; then
ok=$(echo "$info" | jq -r '.ok')
url=$(echo "$info" | jq -r '.result.url // empty')
pending=$(echo "$info"| jq -r '.result.pending_update_count // 0')
err=$(echo "$info" | jq -r '.result.last_error_message // empty')
errdate=$(echo "$info"| jq -r '.result.last_error_date // empty')
apierr=$(echo "$info" | jq -r '.description // empty')
else
ok=$(echo "$info" | grep -oE '"ok":[[:space:]]*(true|false)' | grep -oE '(true|false)')
url=$(echo "$info" | grep -oE '"url":[[:space:]]*"[^"]*"' | sed -E 's/.*"url":[[:space:]]*"([^"]*)".*/\1/')
pending=$(echo "$info"| grep -oE '"pending_update_count":[[:space:]]*[0-9]+' | grep -oE '[0-9]+$')
err=$(echo "$info" | grep -oE '"last_error_message":[[:space:]]*"[^"]*"' | sed -E 's/.*"last_error_message":[[:space:]]*"([^"]*)".*/\1/')
errdate=$(echo "$info"| grep -oE '"last_error_date":[[:space:]]*[0-9]+' | grep -oE '[0-9]+$')
apierr=$(echo "$info" | grep -oE '"description":[[:space:]]*"[^"]*"' | sed -E 's/.*"description":[[:space:]]*"([^"]*)".*/\1/')
[ -z "$pending" ] && pending=0
fi
# Telegram-level API failure (e.g. invalid/revoked token)
if [ "$ok" != "true" ]; then
_kv "Status" "$(_dot bad) ${C_BAD}API error${CR}"
[ -n "$apierr" ] && printf " ${C_BAD}Error:${CR} %s\n" "$apierr"
return
fi
# Webhook URL
if [ -n "$url" ]; then
_kv "URL" "$(_dot ok) ${C_OK}set${CR} ${C_DIM}(${url})${CR}"
else
_kv "URL" "$(_dot bad) ${C_BAD}not set${CR}"
fi
_kv "Pending" "${C_DIM}${pending} update(s)${CR}"
# Last delivery error reported by Telegram
if [ -n "$err" ]; then
when=""
[ -n "$errdate" ] && when=$(date -d "@$errdate" '+%Y-%m-%d %H:%M' 2>/dev/null)
_kv "Last error" "$(_dot bad) ${C_BAD}${err}${CR}"
[ -n "$when" ] && _kv "Error time" "${C_DIM}${when}${CR}"
else
_kv "Last error" "$(_dot ok) ${C_OK}none${CR}"
fi
}
system_section() {
local php_v apache_s mysql_s ip os
php_v=$(php -r 'echo PHP_VERSION;' 2>/dev/null); [ -z "$php_v" ] && php_v="n/a"
apache_s=$(systemctl is-active apache2 2>/dev/null || echo "inactive")
mysql_s=$(systemctl is-active mysql 2>/dev/null || echo "inactive")
ip=$(get_server_ip)
if [ -f /etc/os-release ]; then os=$(. /etc/os-release; echo "$PRETTY_NAME"); else os="Unknown"; fi
_svc_row() { if [ "$2" = "active" ]; then _kv "$1" "$(_dot ok) ${C_OK}active${CR}"; else _kv "$1" "$(_dot bad) ${C_BAD}$2${CR}"; fi; }
_sec "System"
_kv "OS" "${C_DIM}${os}${CR}"
_kv "PHP" "${C_DIM}${php_v}${CR}"
_svc_row "Apache" "$apache_s"
_svc_row "MySQL" "$mysql_s"
_kv "Server IP" "${C_DIM}${ip}${CR}"
}
resources_section() {
local mem_t mem_u mem_p disk load cores up
mem_t=$(free -m 2>/dev/null | awk '/^Mem:/{print $2}')
mem_u=$(free -m 2>/dev/null | awk '/^Mem:/{print $3}')
if [ -n "$mem_t" ] && [ "$mem_t" -gt 0 ] 2>/dev/null; then mem_p=$(( mem_u * 100 / mem_t )); else mem_p=0; fi
disk=$(df -h / 2>/dev/null | awk 'NR==2{print $3" / "$2" ("$5")"}')
load=$(awk '{print $1", "$2", "$3}' /proc/loadavg 2>/dev/null)
cores=$(nproc 2>/dev/null)
up=$(uptime -p 2>/dev/null | sed 's/^up //')
[ -z "$up" ] && up="n/a"
_sec "Resources"
_kv "RAM" "${C_DIM}${mem_u}MB / ${mem_t}MB (${mem_p}%)${CR}"
_kv "Disk" "${C_DIM}${disk}${CR}"
_kv "CPU load" "${C_DIM}${load} (${cores} cores)${CR}"
_kv "Uptime" "${C_DIM}${up}${CR}"
}
function show_logo() {
clear
banner
version_section
bot_section
webhook_section
system_section
resources_section
}
# Renew (or issue) the SSL certificate for the bot's domain.
function renew_ssl() {
clear
banner
_sec "Renew SSL certificate"
# 1) Detect the bot domain: prefer config.php, then saved install state
local cfg="/var/www/html/mirzaprobotconfig/config.php"
local domain=""
if [ -f "$cfg" ]; then
domain=$(grep -E "\\\$domainhosts" "$cfg" 2>/dev/null | head -1 | cut -d"'" -f2)
fi
[ -z "$domain" ] && domain="$(state_get DOMAIN)"
if [ -z "$domain" ]; then
printf " ${C_PROMPT}❯${CR} Enter the bot domain: "
read -r domain
fi
if [ -z "$domain" ]; then
echo -e " ${C_BAD}●${CR} ${C_BAD}No domain found. Aborting.${CR}"
sleep 1; show_menu; return 1
fi
_kv "Domain" "${C_KEY}${domain}${CR}"
if ! command -v certbot >/dev/null 2>&1; then
echo -e " ${C_BAD}●${CR} ${C_BAD}certbot is not installed. Install Mirza first.${CR}"
sleep 1; show_menu; return 1
fi
# Show current expiry, if a certificate already exists
local certfile="/etc/letsencrypt/live/${domain}/cert.pem"
if [ -f "$certfile" ]; then
local exp
exp=$(openssl x509 -enddate -noout -in "$certfile" 2>/dev/null | cut -d= -f2)
[ -n "$exp" ] && _kv "Expires" "${C_DIM}${exp}${CR}"
else
echo -e " ${C_WARN}!${CR} ${C_WARN}No existing certificate found - a new one will be issued.${CR}"
fi
echo ""
# 2) Optional force (Let's Encrypt normally renews only within ~30 days of expiry)
printf " ${C_PROMPT}❯${CR} Force renewal now even if not near expiry? ${C_DIM}[y/N]${CR}: "
read -r _force
local force_flag=""
[[ "$_force" =~ ^[Yy]$ ]] && force_flag="--force-renewal"
echo ""
# Use the apache authenticator so it works while Apache is running (no downtime).
# certonly updates the existing cert lineage in place; Apache already points at it.
run_step "Renewing certificate for ${domain}" \
"certbot certonly --apache --non-interactive --agree-tos --register-unsafely-without-email --keep-until-expiring --cert-name '${domain}' -d '${domain}' ${force_flag}" \
|| { show_step_error; echo -e "\n ${C_BAD}●${CR} ${C_BAD}Renewal failed. See the details above.${CR}"; echo ""; printf " ${C_PROMPT}❯${CR} Press Enter to return to the menu... "; read -r _; show_menu; return 1; }
run_step "Reloading Apache" "systemctl reload apache2 2>/dev/null || systemctl restart apache2"
_sec "Done"
_kv "Domain" "${C_KEY}${domain}${CR}"
if [ -f "$certfile" ]; then
local newexp
newexp=$(openssl x509 -enddate -noout -in "$certfile" 2>/dev/null | cut -d= -f2)
[ -n "$newexp" ] && _kv "Valid until" "${C_OK}${newexp}${CR}"
fi
echo ""
printf " ${C_PROMPT}❯${CR} Press Enter to return to the menu... "
read -r _
show_menu
}
function show_menu() {
show_logo
_sec "Menu"
_mi "1" "Install Mirza"
_mi "2" "Update Mirza"
_mi "3" "Remove Mirza"
_mi "4" "Migrate: Free -> Pro (Beta)"
_mi "5" "Renew SSL certificate"
_mi "6" "Help & Parameters"
_mi "7" "Exit"
_rule
echo ""
printf " ${C_PROMPT}❯${CR} Select an option ${C_DIM}[1-7]${CR}: "
read -r option
case $option in
1) install_bot ;;
2) update_bot ;;
3) remove_bot ;;
4) migrate_to_pro ;;
5) renew_ssl ;;
6) show_help_screen ;;
7) echo -e "\n${C_OK}Exiting...${CR}"; exit 0 ;;
*) echo -e "\n${C_BAD}Invalid option. Please try again.${CR}"; sleep 1; show_menu ;;
esac
}
# Clean, styled guide of all commands and parameters
function show_help_screen() {
clear
banner
_sec "Commands"
_kv "install" "${C_DIM}Install Mirza${CR}"
_kv "update" "${C_DIM}Update Mirza (choose channel / version)${CR}"
_kv "remove" "${C_DIM}Remove Mirza and its services${CR}"
_kv "migrate" "${C_DIM}Migrate Free -> Pro${CR}"
_kv "renew" "${C_DIM}Renew the bot domain SSL certificate${CR}"
_kv "menu" "${C_DIM}Open this interactive panel (default)${CR}"
_sec "Install parameters"
_kv "--name" "${C_DIM}Bot username${CR}"
_kv "--token" "${C_DIM}Telegram bot token${CR}"
_kv "--admin" "${C_DIM}Admin chat id${CR}"
_kv "--domain" "${C_DIM}Domain name (e.g. bot.example.com)${CR}"
_kv "--db-user" "${C_DIM}Database username${CR}"
_kv "--db-pass" "${C_DIM}Database password${CR}"
_sec "Source parameters"
_kv "--version" "${C_DIM}Specific release tag (e.g. 0.1.7)${CR}"
_kv "--channel" "${C_DIM}beta | release | auto${CR}"
_kv "-h, --help" "${C_DIM}Show CLI help and exit${CR}"
_sec "Examples"
printf " ${C_KEY}mirza install --channel auto${CR}\n"
printf " ${C_KEY}mirza install --name myvpnbot --token 123:ABC \\\\${CR}\n"
printf " ${C_DIM} --admin 111 --domain bot.example.com --version 0.1.7${CR}\n"
printf " ${C_KEY}mirza update --version 0.1.6${CR}\n"
printf " ${C_KEY}mirza update --channel release${CR}\n"
printf " ${C_KEY}mirza remove${CR}\n"
echo ""
_rule
echo ""
printf " ${C_PROMPT}❯${CR} Press Enter to return to the menu... "
read -r _
show_menu
}
function find_free_port() {
for port in {3300..3330}; do
if ! ss -tuln | grep -q ":$port "; then
echo "$port"
return 0
fi
done
echo -e "\033[31m[ERROR] No free port found between 3300 and 3330.\033[0m"
exit 1
}
function fix_update_issues() {
echo -e "\e[33mTrying to fix update issues by changing mirrors...\033[0m"
# Broken apt mirrors are often a DNS problem - fix DNS first
ensure_dns
cp /etc/apt/sources.list /etc/apt/sources.list.backup
if [ -f /etc/os-release ]; then
. /etc/apt/sources.list
VERSION_ID=$(cat /etc/os-release | grep VERSION_ID | cut -d '"' -f2)
UBUNTU_CODENAME=$(cat /etc/os-release | grep UBUNTU_CODENAME | cut -d '=' -f2)
else
echo -e "\e[91mCould not detect Ubuntu version.\033[0m"
return 1
fi
MIRRORS=(
"archive.ubuntu.com"
"us.archive.ubuntu.com"
"fr.archive.ubuntu.com"
"de.archive.ubuntu.com"
"mirrors.digitalocean.com"
"mirrors.linode.com"
)
for mirror in "${MIRRORS[@]}"; do
echo -e "\e[33mTrying mirror: $mirror\033[0m"
cat > /etc/apt/sources.list << EOF
deb http://$mirror/ubuntu/ $UBUNTU_CODENAME main restricted universe multiverse
deb http://$mirror/ubuntu/ $UBUNTU_CODENAME-updates main restricted universe multiverse
deb http://$mirror/ubuntu/ $UBUNTU_CODENAME-security main restricted universe multiverse
EOF
if apt-get update 2>/dev/null; then
echo -e "\e[32mSuccessfully updated using mirror: $mirror\033[0m"
return 0
fi
done
mv /etc/apt/sources.list.backup /etc/apt/sources.list
echo -e "\e[91mAll mirrors failed. Restored original sources.list\033[0m"
return 1
}
# ─────────────────────────────────────────────────────────────
# Validation and pre-flight checks
# (DNS helpers dns_works/ensure_dns are defined near the top)
# ─────────────────────────────────────────────────────────────
# Can we actually reach the internet?
net_works() {
curl -fsSL --max-time 8 -o /dev/null "https://github.com" 2>/dev/null && return 0
curl -fsSL --max-time 8 -o /dev/null "https://api.telegram.org" 2>/dev/null && return 0
return 1
}
# Ensure DNS + connectivity, fixing DNS automatically if needed.
ensure_connectivity() {
ensure_dns
net_works && return 0
echo -e " ${C_WARN}!${CR} ${C_WARN}No connectivity - resetting DNS and retrying...${CR}"
ensure_dns
net_works && return 0
return 1
}
# ── Input validators ─────────────────────────────────────────
validate_domain() { [[ "$1" =~ ^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$ ]]; }
# 0 = points here, 1 = points elsewhere, 2 = could not resolve
domain_points_here() {
local dom="$1" myip resolved
myip=$(get_server_ip)
resolved=$(getent ahostsv4 "$dom" 2>/dev/null | awk '{print $1; exit}')
[ -z "$resolved" ] && resolved=$(getent hosts "$dom" 2>/dev/null | awk '{print $1; exit}')
[ -z "$resolved" ] && return 2
[ "$resolved" = "$myip" ] && return 0
return 1
}
# 0 = valid+live, 1 = bad format, 2 = format ok but token rejected/unreachable
validate_token() {
[[ "$1" =~ ^[0-9]{8,10}:[a-zA-Z0-9_-]{35}$ ]] || return 1
local r; r=$(curl -fsSL --max-time 8 "https://api.telegram.org/bot$1/getMe" 2>/dev/null)
echo "$r" | grep -q '"ok":true' && return 0
return 2
}