forked from erfjab/Backuper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
install.sh
968 lines (853 loc) · 31.8 KB
/
install.sh
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
#!/bin/bash
colors=( "\033[1;31m" "\033[1;35m" "\033[1;92m" "\033[38;5;46m" "\033[1;38;5;208m" "\033[1;36m" "\033[0m" )
red=${colors[0]} pink=${colors[1]} green=${colors[2]} spring=${colors[3]} orange=${colors[4]} cyan=${colors[5]} reset=${colors[6]}
print() { echo -e "${cyan}$1${reset}"; }
error() { echo -e "${red}✗ $1${reset}"; }
success() { echo -e "${spring}✓ $1${reset}"; }
log() { echo -e "${green}! $1${reset}"; }
input() { read -p "$(echo -e "${orange}▶ $1${reset}")" "$2"; }
confirm() { read -p "$(echo -e "\n${pink}Press any key to continue...${reset}")"; }
trap 'echo -e "\n"; error "Script interrupted! Contact: @ErfJabs"; exit 1' SIGINT
check_needs() {
log "Checking root..."
[ "$EUID" -eq 0 ] || { error "Run as root."; exit 1; }
if command -v apt-get &> /dev/null; then
PKG_MANAGER="apt-get"
PKG_UPDATE="$PKG_MANAGER update -y"
PKG_INSTALL="$PKG_MANAGER install -y"
MYSQL_CLIENT_PKG="mysql-client"
elif command -v dnf &> /dev/null; then
PKG_MANAGER="dnf"
PKG_UPDATE="$PKG_MANAGER check-update"
PKG_INSTALL="$PKG_MANAGER install -y"
MYSQL_CLIENT_PKG="mysql"
elif command -v yum &> /dev/null; then
PKG_MANAGER="yum"
PKG_UPDATE="$PKG_MANAGER check-update"
PKG_INSTALL="$PKG_MANAGER install -y"
MYSQL_CLIENT_PKG="mysql"
else
error "No supported package manager found. Please install packages manually."
exit 1
fi
log "Checking for system updates..."
$PKG_UPDATE || true
packages_to_install=()
for pkg in curl wget zip cron $MYSQL_CLIENT_PKG; do
if ! command -v $pkg &> /dev/null; then
log "Need to install $pkg"
packages_to_install+=($pkg)
else
log "$pkg is already installed."
fi
done
ARCH=$(uname -m)
if [ "$ARCH" == "x86_64" ]; then
YQ_BINARY="yq_linux_amd64"
elif [ "$ARCH" == "aarch64" ]; then
YQ_BINARY="yq_linux_arm64"
else
error "Unsupported architecture: $ARCH"
exit 1
fi
if ! command -v yq &> /dev/null; then
log "Need to install yq"
need_yq=true
else
log "yq is already installed."
fi
if ! command -v 7z &> /dev/null; then
log "Need to install p7zip"
if [ "$PKG_MANAGER" = "apt-get" ]; then
packages_to_install+=(p7zip-full)
else
packages_to_install+=(p7zip)
fi
else
log "p7zip is already installed."
fi
if [ ${#packages_to_install[@]} -ne 0 ]; then
log "Installing missing packages: ${packages_to_install[*]}"
$PKG_INSTALL "${packages_to_install[@]}" || { error "Package installation failed."; exit 1; }
fi
if [ "$need_yq" = true ]; then
log "Downloading yq for architecture $ARCH..."
wget "https://github.com/mikefarah/yq/releases/latest/download/$YQ_BINARY" -O /usr/bin/yq || { error "Failed to download yq."; exit 1; }
chmod +x /usr/bin/yq || { error "Failed to set execute permissions on yq."; exit 1; }
log "yq installed successfully."
fi
if ! systemctl is-active --quiet cron; then
log "Starting cron service..."
systemctl start cron || { error "Failed to start cron service."; exit 1; }
fi
if ! systemctl is-enabled --quiet cron; then
log "Enabling cron service to start on boot..."
systemctl enable cron || { error "Failed to enable cron service."; exit 1; }
fi
# Verify mysqldump installation
if ! command -v mysqldump &> /dev/null; then
error "mysqldump is not installed. Please check your MySQL client installation."
exit 1
fi
success "All necessary packages are installed and cron service is running."
sleep 1
}
menu() {
while true; do
print "\n\t Welcome to Backuper!"
print "\t\t version 0.2.5 by @ErfJab"
print "—————————————————————————————————————————————————————————————————————————"
print "1) Install"
print "2) Manage"
print "0) Exit"
print ""
input "Enter your option number: " option
clear
case $option in
1)
start_advenced_backup
;;
2)
manage_backups
;;
0)
print "Thank you for using @ErfJabs script. Goodbye!"
exit 0
;;
*)
error "Invalid option, Please select a valid option!"
;;
esac
done
}
manage_backups() {
local backup_scripts=($(find /root/ -name "*_backuper.sh" -o -name "ac-backup*.sh"))
if [ ${#backup_scripts[@]} -eq 0 ]; then
success "No active backup scripts found."
sleep 1
return
fi
print "\nActive backup scripts:\n"
for i in "${!backup_scripts[@]}"; do
print "$((i+1))) ${backup_scripts[$i]}"
done
print ""
while true; do
input "Enter the number of the backup to stop (or 'q' to quit): " choice
if [[ "$choice" == "q" ]]; then
return
elif [[ "$choice" =~ ^[0-9]+$ ]] && [ "$choice" -ge 1 ] && [ "$choice" -le "${#backup_scripts[@]}" ]; then
local script="${backup_scripts[$((choice-1))]}"
local script_name=$(basename "$script")
if crontab -l | grep -q "$script_name"; then
crontab -l | grep -v "$script_name" | crontab -
success "Stopped backup: $script_name"
else
print "No cron job found for: $script_name"
fi
if rm "$script"; then
success "Removed script file: $script_name"
else
error "Failed to remove script file: $script_name"
fi
else
error "Invalid choice. Enter a number between 1 and ${#backup_scripts[@]}."
fi
done
success "Selected backup stopped and script removed."
sleep 1
clear
}
backup_template() {
clear
print "[TEMPLATE]\n"
print "Choose a backup template. You can add or remove custom directories after selecting.\n"
print "1) Marzban"
print "2) Marzban Logs"
print "3) All X-ui's"
print "4) Hiddify Manager"
print "5) Marzneshin"
print "6) Mirza Bot"
print "0) Custom"
print ""
while true; do
input "Enter your template number: " template
case $template in
1)
marzban_template
break
;;
2)
success "You chose marzban logs."
marzban_logs=true
break
;;
3)
xui_template
break
;;
4)
hiddify_template
break
;;
5)
marzneshin_template
break
;;
6)
mirzabot_template
break
;;
0)
success "You Chose Custom"
break
;;
*)
error "Invalid option. Please choose a valid number!"
;;
esac
done
}
marzneshin_template() {
log "Checking Marzneshin configuration..."
local docker_compose_file="/etc/opt/marzneshin/docker-compose.yml"
if [ ! -f "$docker_compose_file" ]; then
error "Docker compose file not found: $docker_compose_file"
exit 1
else
success "Docker compose file found: $docker_compose_file"
fi
log "Analyzing Marzneshin database configuration..."
local db_type=$(yq eval '.services.db.image' "$docker_compose_file")
local db_name=$(yq eval '.services.db.environment.MARIADB_DATABASE // .services.db.environment.MYSQL_DATABASE' "$docker_compose_file")
local db_password=$(yq eval '.services.db.environment.MARIADB_ROOT_PASSWORD // .services.db.environment.MYSQL_ROOT_PASSWORD' "$docker_compose_file")
local db_port=$(yq eval '.services.db.ports[0]' "$docker_compose_file" | cut -d':' -f2)
if [[ "$db_type" == *"mariadb"* ]]; then
success "Database type: MariaDB"
elif [[ "$db_type" == *"mysql"* ]]; then
success "Database type: MySQL"
else
error "Unsupported database type: $db_type"
exit 1
fi
success "Database name: $db_name"
success "Database port: $db_port"
if [ -z "$db_password" ]; then
error "Database password not found in docker-compose.yml"
exit 1
else
success "Database password found"
fi
log "Setting up backup for Marzneshin database..."
local db_backup_path="/root/${name}_marzneshin_db_backup.sql"
mysql_database["marzneshin"]="marzneshin:${db_name}:${db_password}:${db_port}"
log "Adding Marzneshin directories to backup list..."
directories=()
add_directories() {
local base_dir="$1"
while IFS= read -r -d '' item; do
if [[ ! "$item" =~ /mysql ]]; then
success "$item"
directories+=("$item")
fi
done < <(find "$base_dir" -mindepth 1 -print0)
}
log "Scanning volume: /var/lib/marzneshin"
add_directories "/var/lib/marzneshin"
log "Scanning volume: /etc/opt/marzneshin"
add_directories "/etc/opt/marzneshin"
log "Listing volumes from docker-compose..."
services=$(yq eval '.services | keys | .[]' "$docker_compose_file")
for service in $services; do
volumes=$(yq eval ".services.$service.volumes | .[]" "$docker_compose_file" 2>/dev/null | awk -F ':' '{print $1}')
if [ -n "$volumes" ]; then
for volume in $volumes; do
if [[ -d "$volume" && ! "$volume" =~ /mysql && ! "$volume" =~ /mariadb ]]; then
log "Scanning volume: $volume for service: $service"
add_directories "$volume"
elif [[ -d "$volume" ]]; then
log "Skipping database volume: $volume for service: $service"
else
error "Volume $volume for service $service does not exist or is not a directory."
fi
done
fi
done
success "Marzneshin backup configuration complete"
sleep 2
}
mirzabot_template() {
log "Checking mirzabot backup..."
local mirzabot_file='/var/www/html/mirzabotconfig/config.php'
if [ ! -f "$mirzabot_file" ]; then
error "Backup file does not exist."
exit 1
else
success "$mirzabot_file Backup file exists."
fi
# Extract database values from config.php
dbname=$(grep -m 1 "\$dbname" $mirzabot_file | sed -E "s/.*dbname\s*=\s*'([^']+)'.*/\1/")
usernamedb=$(grep -m 1 "\$usernamedb" $mirzabot_file | sed -E "s/.*usernamedb\s*=\s*'([^']+)'.*/\1/")
passworddb=$(grep -m 1 "\$passworddb" $mirzabot_file | sed -E "s/.*passworddb\s*=\s*'([^']+)'.*/\1/")
# Check if the values are extracted correctly
if [ -z "$dbname" ] || [ -z "$usernamedb" ] || [ -z "$passworddb" ]; then
error "Failed to extract database values from $mirzabot_file."
exit 1
else
success "Database Name: $dbname"
success "Database Username: $usernamedb"
success "Database Password: $passworddb"
# Initialize the array if not already done
declare -gA mirza_database
mirza_database["$dbname"]="${dbname}:${usernamedb}:${passworddb}"
sleep 1
fi
}
hiddify_template() {
log "Checking hiddify backup..."
local hiddify_file="/opt/hiddify-manager/hiddify-panel/backup.sh"
if [ ! -f "$hiddify_file" ]; then
error "Backup file does not exist."
exit 1
else
success "$hiddify_file Backup file exists."
hiddify_backup=true
fi
}
marzban_template() {
log "Checking docker-compose file..."
local docker_compose_file="/opt/marzban/docker-compose.yml"
if ! grep -q "^services:" "$docker_compose_file"; then
error "Docker compose file not found or invalid format: $docker_compose_file"
exit 1
else
success "Docker compose file found."
fi
log "Reviewing services..."
services=$(yq eval '.services | keys | .[]' "$docker_compose_file")
if [ -z "$services" ]; then
error "No services found in the docker-compose file."
exit 1
fi
for service in $services; do
depends_on=$(yq eval ".services.$service.depends_on | .[]" "$docker_compose_file" 2>/dev/null)
if [ -z "$depends_on" ]; then
dependent_services=$(grep -E "^\s+[a-zA-Z0-9_-]+:" "$docker_compose_file" | awk -F ':' '{print $1}' | awk '{$1=$1};1' | grep -v "^$service$")
if [ -n "$dependent_services" ]; then
for dependent_service in $dependent_services; do
dependencies=$(yq eval ".services.$dependent_service.depends_on | .[]" "$docker_compose_file" 2>/dev/null)
if [[ "$dependencies" =~ (^|[[:space:]])"$service"($|[[:space:]]) ]]; then
depends_on="$dependent_service"
break
fi
done
fi
fi
if [ -z "$depends_on" ]; then
db_type="SQLite"
db_name="sqlite.db"
else
db_type="mysql"
db_name=$(yq eval ".services.$depends_on.environment.MYSQL_DATABASE" "$docker_compose_file" 2>/dev/null)
if [ -z "$db_name" ]; then
continue
fi
fi
env_file=$(yq eval ".services.$service.env_file" "$docker_compose_file" 2>/dev/null)
volumes=$(yq eval ".services.$service.volumes | .[]" "$docker_compose_file" 2>/dev/null | awk -F ':' '{print $1}')
if [ "$service" != "phpmyadmin" ] && [ "$db_name" != "null" ]; then
success "Service: $service"
success "Env file: $env_file"
success "Volumes: $volumes"
print ""
sleep 1
success "Database type: $db_type"
print ""
sleep 1
success "Database name: $db_name"
service_info["$service"]="${service}:${volumes}"
if [[ "$db_type" == "mysql" ]]; then
local env_file="/opt/marzban/$env_file"
if [[ -f "$env_file" ]]; then
SQLALCHEMY_DATABASE_URL=$(grep -v '^#' "$env_file" | grep 'SQLALCHEMY_DATABASE_URL' | cut -d '=' -f2- | tr -d ' ')
MYSQL_ROOT_PASSWORD=$(grep -v '^#' "$env_file" | grep 'MYSQL_ROOT_PASSWORD' | cut -d '=' -f2- | tr -d ' ')
if [ -z "$SQLALCHEMY_DATABASE_URL" ] || [ -z "$MYSQL_ROOT_PASSWORD" ]; then
error "Missing parameters in $env_file."
exit 1
else
db_url="$SQLALCHEMY_DATABASE_URL"
db_password="$MYSQL_ROOT_PASSWORD"
fi
else
error "Environment file not found: $env_file"
exit 1
fi
success "Database URL: $db_url"
success "Database password: $db_password"
mysql_database["$service"]="${service}:${db_name}:${MYSQL_ROOT_PASSWORD}"
fi
fi
done
log "Listing volumes..."
directories=()
log "Scanning volume: /opt/marzban"
mapfile -t items < <(find "/opt/marzban" -mindepth 1 -maxdepth 1 -type d \( -name "*mysql*" -prune \) -o -print)
for item in "${items[@]}"; do
success "$item"
directories+=("$item")
done
for service in "${!service_info[@]}"; do
IFS=':' read -r name volume <<< "${service_info[$service]}"
if [[ -d "$volume" ]]; then
log "Scanning volume: $volume for service: $name"
mapfile -t items < <(find "$volume" -mindepth 1 -maxdepth 1 -type d \( -name "*mysql*" -prune \) -o -print)
for item in "${items[@]}"; do
success "$item"
directories+=("$item")
done
else
error "Volume $volume for service $name does not exist or is not a directory."
exit 1
fi
done
sleep 2
}
xui_template() {
log "Checking x-ui db..."
directories=()
local db_path="/etc/x-ui/x-ui.db"
if [ ! -f "$db_path" ]; then
error "Database file not found: $db_path"
exit 1
else
success "Database file found: $db_path"
directories+=("$db_path")
fi
log "Adding directories for x-ui"
local xui_directory="/etc/x-ui"
mapfile -t items < <(find "$xui_directory" -mindepth 1 -maxdepth 1 -type d)
for item in "${items[@]}"; do
success "$item"
directories+=("$item")
done
for dir in "${directories[@]}"; do
success "Directory found: $dir"
done
sleep 2
}
backup_custom_dir() {
clear
print "[CUSTOM DIR]\n"
print "Add custom directories or files to the backup (e.g., /etc/haproxy or /root/ErfJab/holderbot.db)."
while true; do
print "\nCurrent directories:"
for dir in "${directories[@]}"; do
[[ -n "$dir" ]] && success "\t- $dir"
done
print ""
input "Enter a path (or 'done' to finish): " path
if [[ "$path" == "done" ]]; then
break
elif [[ ! -e "$path" ]]; then
error "Path does not exist: $path"
elif [[ " ${directories[*]} " =~ " ${path} " ]]; then
directories=("${directories[@]/$path}")
success "Removed from list: $path"
else
directories+=("$path")
success "Added to list: $path"
fi
done
}
start_advenced_backup() {
check_needs
backup_template
backup_custom_dir
backup_name
backup_cronjob
backup_caption
backup_password
send_to
backup_compression
backup_generate
}
backup_name() {
clear
print "[NAME]\n"
print "We need a name for the backup file (e.g., Master, panel, ErfJab).\n"
while true; do
input "Enter a name: " name
if ! [[ "$name" =~ ^[a-zA-Z0-9_]+$ ]]; then
error "Name must contain only letters, numbers, or underscores."
elif [ ${#name} -lt 3 ]; then
error "Name must be at least 3 characters long."
elif [ -e "${name}_backuper.sh" ]; then
error "File ${name}_backuper.sh already exists. Choose a different name."
else
success "Backup name: $name"
break
fi
done
sleep 1
}
backup_caption() {
clear
print "[CAPTION]\n"
print "You can add a caption for your backup file (e.g., 'The main server of the company').\n"
input "Enter your caption (Press Enter to skip): " caption
if [ -z "$caption" ]; then
success "No caption provided. Skipping..."
caption=""
else
caption+='\n'
success "Caption set: $caption"
fi
sleep 1
}
backup_cronjob() {
clear
print "[CRONJOB]\n"
print "Enter a time interval in minutes for sending backups."
print "For example, '10' means backups will be sent every 10 minutes.\n"
while true; do
input "Enter the number of minutes (1-1440): " minutes
if ! [[ "$minutes" =~ ^[0-9]+$ ]]; then
error "Please enter a valid number."
elif [ "$minutes" -lt 1 ] || [ "$minutes" -gt 1440 ]; then
error "Number must be between 1 and 1440."
else
break
fi
done
if [ "$minutes" -le 59 ]; then
cron_time="*/$minutes * * * *"
elif [ "$minutes" -le 1439 ]; then
hours=$((minutes / 60))
remaining_minutes=$((minutes % 60))
if [ "$remaining_minutes" -eq 0 ]; then
cron_time="0 */$hours * * *"
else
cron_time="*/$remaining_minutes */$hours * * *"
fi
else
cron_time="0 0 * * *"
fi
success "Cron job set to run every $minutes minutes: $cron_time"
sleep 1
}
send_to() {
clear
print "[PLATFORM]\n"
print "Select one platform to send your backup.\n"
print "1) Telegram"
print "2) Discord\n"
while true; do
input "Enter your choice (1 or 2): " send_to_option
case $send_to_option in
1)
send_to_telegram
break
;;
2)
send_to_discord
break
;;
*)
error "Invalid option. Please select 1 for Telegram or 2 for Discord."
;;
esac
done
sleep 1
}
send_to_telegram() {
clear
print "[TELEGRAM]\n"
print "To use Telegram, you need to provide a bot token and a chat ID.\n"
while true; do
input "Enter the bot token: " bot_token
if [[ -z "$bot_token" ]]; then
error "Bot token cannot be empty!"
elif [[ ! "$bot_token" =~ ^[0-9]+:[a-zA-Z0-9_-]{35}$ ]]; then
error "Invalid bot token format!"
else
break
fi
done
while true; do
input "Enter the chat ID: " chat_id
if [[ -z "$chat_id" ]]; then
error "Chat ID cannot be empty!"
elif [[ ! "$chat_id" =~ ^-?[0-9]+$ ]]; then
error "Invalid chat ID format!"
else
log "Checking Telegram bot..."
response=$(curl -s -o /dev/null -w "%{http_code}" -X POST "https://api.telegram.org/bot$bot_token/sendMessage" -d chat_id="$chat_id" -d text="Backuper Test Message!")
if [[ "$response" -ne 200 ]]; then
error "Invalid bot token or chat ID, or Telegram API error!"
else
success "Bot token and chat ID are valid."
sleep 1
break
fi
fi
done
sleep 1
}
send_to_discord() {
clear
print "[DISCORD]\n"
print "To use Discord, you need to provide a webhook URL."
print "If you don't know how to get this, check: www.google.com/how_to_create_discord_webhook\n"
while true; do
input "Enter the webhook URL: " webhook_url
if [[ -z "$webhook_url" ]]; then
error "Webhook URL cannot be empty!"
elif [[ ! "$webhook_url" =~ ^https://discord(app)?\.com/api/webhooks/[0-9]+/[a-zA-Z0-9_-]+$ ]]; then
error "Invalid webhook URL format!"
else
log "Checking Discord webhook..."
response=$(curl -s -o /dev/null -w "%{http_code}" -X POST -H "Content-Type: application/json" -d '{"content": "Backuper Test Message!"}' "$webhook_url")
if [[ "$response" -ne 204 ]]; then
error "Invalid webhook URL or Discord API error!"
else
success "Webhook URL is valid."
sleep 1
break
fi
fi
done
sleep 1
}
backup_compression() {
clear
print "[COMPRESSION]\n"
print "Select a compression method for your backup:"
print "1) ZIP (.zip) | Compression: Normal (✗) - Size: Normal (✗) - CPU: Low (✓)"
print "2) 7z (.7z) | Compression: High (✓) - Size: Minimum (✓) - CPU: High (✗)\n"
while true; do
input "Enter your choice (1 or 2): " compression
case $compression in
1)
compression_ext=".zip"
compression_cmd="zip -9 -r"
compression_update="zip -9 -u"
break
;;
2)
compression_ext=".7z"
compression_cmd="7z a -mx=9 -mhe=on -t7z"
compression_update="7z u -mx=9 -mhe=on"
break
;;
*)
error "Invalid choice. Please select 1 or 2."
;;
esac
done
while true; do
input "Do you want to password protect the archive? (y/n): " use_password
case $use_password in
[Yy]*)
while true; do
input "Enter the password for the archive: " archive_password
input "Confirm the password: " confirm_password
if [ "$archive_password" == "$confirm_password" ]; then
echo "Password confirmed."
if [ "$compression_ext" == ".zip" ]; then
compression_cmd="$compression_cmd -e -P $archive_password"
compression_update="$compression_update -e -P $archive_password"
elif [ "$compression_ext" == ".7z" ]; then
compression_cmd="$compression_cmd -p$archive_password"
compression_update="$compression_update -p$archive_password"
fi
break 2 # Exit both loops
else
echo "Passwords do not match. Please try again."
fi
done
;;
[Nn]*)
break
;;
*)
error "Please answer y or n."
;;
esac
done
if [ "$send_to_option" == "1" ]; then # Telegram
max_file_size=49
elif [ "$send_to_option" == "2" ]; then # Discord
max_file_size=24
fi
# Construct the full compression command
if [ "$compression_ext" == ".zip" ]; then
compression_full_cmd="$compression_cmd -s ${max_file_size}m"
compression_update_cmd="$compression_update -s ${max_file_size}m"
elif [ "$compression_ext" == ".7z" ]; then
compression_full_cmd="$compression_cmd -v${max_file_size}m"
compression_update_cmd="$compression_update -v${max_file_size}m"
fi
sleep 1
}
backup_generate() {
local backup_script="/root/${name}_backuper_.sh"
log "Generating backup script: $backup_script..."
local DB=""
if [ ${#mysql_database[@]} -gt 0 ]; then
for database in "${mysql_database[@]}"; do
IFS=':' read -r service_name db_name db_password db_port <<< "$database"
local db_address="/root/${name}_${db_name}_backuper.sql"
local dump_command
if [ "$service_name" == "marzneshin" ]; then
dump_command="if ! mysqldump -h 127.0.0.1 -P ${db_port} -u root -p'${db_password}' --column-statistics=0 '${db_name}' > '${db_address}'; then
message=\"Failed to backup Marzneshin database ${db_name}. Please check the server.\"
$send_notification_command
exit 1
fi"
else
dump_command="if ! docker exec marzban-mysql-1 mysqldump -u root -p'${db_password}' '${db_name}' > '${db_address}'; then
message=\"Failed to backup database ${db_name}. Please check the server.\"
$send_notification_command
exit 1
fi"
fi
DB+="${dump_command}\n"
directories+=("$db_address")
done
fi
if [ ${#mirza_database[@]} -gt 0 ]; then
for database in "${mirza_database[@]}"; do
IFS=':' read -r dbname usernamedb passworddb <<< "$database"
local db_address="/root/${name}_${dbname}_backuper.sql"
local dump_command="if ! mysqldump -u '${usernamedb}' -p'${passworddb}' '${dbname}' > '${db_address}'; then
message=\"Failed to backup database ${dbname}. Please check the server.\"
$send_notification_command
exit 1
fi"
DB+="${dump_command}\n"
directories+=("$db_address")
done
fi
local LOGS=""
if [ "$marzban_logs" = true ]; then
LOGS+="
if ! marzban logs --no-follow > \"marzban_logs_backuper.log\"; then
message=\"Failed to generate logs. Please check the server.\"
\$send_notification_command
exit 1
fi
"
directories+=("marzban_logs_backuper.log")
rm_commands='rm -f *\"_backuper.log\"'
fi
local COMMANDS=""
if [ "$hiddify_backup" = true ]; then
COMMANDS+="
if ! bash /opt/hiddify-manager/hiddify-panel/backup.sh;then
message=\"Failed to generate hiddify backup. Please check the server.\"
\$send_notification_command
exit 1
fi
"
directories+=("/opt/hiddify-manager/hiddify-panel/backup/*.json")
rm_commands='rm -f "/opt/hiddify-manager/hiddify-panel/backup/"*'
fi
local send_file_command
local send_notification_command
if [ "$send_to_option" == "1" ]; then # Telegram
send_file_command="curl -s -F \"chat_id=$chat_id\" -F \"document=@\$file_to_send\" -F \"caption=\$caption\" -F \"parse_mode=HTML\" \"https://api.telegram.org/bot$bot_token/sendDocument\""
send_notification_command="curl -s -X POST \"https://api.telegram.org/bot$bot_token/sendMessage\" -d \"chat_id=$chat_id\" -d \"text=\$message\" -d \"parse_mode=HTML\""
CAPTION_TEXT="${caption}
📦 From <code>\${ip}</code>
⚡️ Develop by <b>@ErfJabs</b>"
elif [ "$send_to_option" == "2" ]; then # Discord
send_file_command="curl -v -H 'Content-Type: multipart/form-data' -F \"payload_json={\\\"content\\\":\\\"\$caption\\\"}\" -F \"file=@\$file_to_send\" \"$webhook_url\""
send_notification_command="curl -s -H 'Content-Type: application/json' -X POST -d '{\"content\": \"\$message\"}' \"$webhook_url\""
CAPTION_TEXT="${caption} 📦 from \${ip}\n⚡️ Develop by **[@ErfJabs](<https://t.me/ErfJabs>)**"
fi
cat <<EOL > "$backup_script"
#!/bin/bash
set -e
ip=\$(hostname -I | awk '{print \$1}')
timestamp=\$(TZ='Asia/Tehran' date +%m%d-%H%M)
base_name="/root/${name}_\${timestamp}_backuper."
backup_name="/root/${name}_\${timestamp}_backuper${compression_ext}"
caption="${CAPTION_TEXT}"
rm -f *"_backuper."*
rm -f "\$backup_name"*
rm -f *"_backuper.sql"
$(echo -e "$rm_commands")
$(echo -e "$DB")
$(echo -e "$LOGS")
$(echo -e "$COMMANDS")
if ! $compression_full_cmd "\$backup_name" ${directories[@]}; then
message="Failed to compress ${name} files. Please check the server."
echo "\$message"
$send_notification_command
exit 1
fi
if find ${base_name}* -type f > /dev/null 2>&1; then
for file_to_send in ${base_name}*; do
echo "Sending file: $file_to_send"
retry_count=0
max_retries=4
while [ $retry_count -lt $max_retries ]; do
if $send_file_command; then
echo "Backup All part sent Successfully: $file_to_send"
break
else
retry_count=$((retry_count+1))
echo "Failed to send $file_to_send. Retrying... Attempt $retry_count"
sleep 3
fi
if [ $retry_count -eq $max_retries ]; then
message="Failed to send ${name} backup part: $file_to_send after $max_retries attempts. Please check the server."
echo "$message"
$send_notification_command
exit 1
fi
done
done
echo "All backup parts sent successfully"
else
message="Backup file not found: $base_name. Please check the server."
echo "$message"
$send_notification_command
exit 1
fi
rm -f "\$base_name"*
rm -f *"_backuper.sql"
$(echo -e "$rm_commands")
EOL
chmod +x "$backup_script"
success "Backup script created: $backup_script"
log "Running the backup script..."
if output=$(bash "$backup_script"); then
success "Backup script run successfully."
log "Setting up cron job..."
if (crontab -l 2>/dev/null; echo "$cron_time $backup_script") | crontab -; then
success "Cron job set up successfully. Backups will run every $minutes minutes."
else
error "Failed to set up cron job. Set it up manually: $cron_time $backup_script"
exit 1
fi
success "🎉 Your backup system is set up and running!"
success "Backup script location: $backup_script"
success "Cron job: Every $minutes minutes"
success "First backup created and sent."
success "Thank you for using @ErfJabs backup script. Enjoy automated backups!"
exit 1
else
error "Failed to run backup script. Output:"
error "$output"
message="Backup script failed to run. Please check the server."
eval "$send_notification_command"
exit 1
fi
}
run() {
cd
clear
menu
}
run