-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript_debian.sh
More file actions
2377 lines (2045 loc) · 99.1 KB
/
script_debian.sh
File metadata and controls
2377 lines (2045 loc) · 99.1 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
# Attempt to set pipefail, but don't error if not supported
if (set -o pipefail 2>/dev/null); then
set -euo pipefail
echo "DEBUG: pipefail is supported and set." >&2
else
set -eu # Continue with error checking and unset variable checking
# Use direct echo to LOG_FILE as log_message function may not be defined yet
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Warning: set -o pipefail is not supported by this shell. Pipeline behavior might differ." >>"$LOG_FILE"
echo "DEBUG: pipefail is NOT supported. Using set -eu." >&2
fi
readonly RED='\033[0;31m'
readonly GREEN='\033[1;32m'
readonly YELLOW='\033[1;33m'
readonly BLUE='\033[0;34m'
readonly PURPLE='\033[0;35m'
readonly CYAN='\033[0;36m'
readonly WHITE='\033[1;37m'
readonly BOLD='\033[1m'
readonly NC='\033[0m'
readonly SCRIPT_VERSION="3.0"
LOG_FILE="/tmp/dezerx-install.log"
LICENSE_KEY=""
DOMAIN=""
INSTALL_DIR=""
DB_PASSWORD=""
DB_NAME_PREFIX=""
DB_FULL_NAME=""
DB_USER_FULL=""
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# LOG_FILE already defined above
OPERATION_MODE=""
BACKUP_DIR=""
DB_BACKUP_FILE=""
RESTORE_ON_FAILURE=""
PROTOCOL="https"
# Initial Debug: Variables initialized.
echo "DEBUG: Global variables initialized." >&2
print_color() {
printf "${1}${2}${NC}\n"
}
check_required_commands() {
local cmds=(curl awk grep sed)
for cmd in "${cmds[@]}"; do
if ! command -v "$cmd" &>/dev/null; then
print_error "Required command '$cmd' not found. Please install it." # print_error uses print_color
exit 1
fi
done
}
log_message() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >>"$LOG_FILE"
}
show_loading() {
local pid=$1
local message=$2
local spin_frames=('⠋' '⠙' '⠹' '⠸' '⠼' '⠴' '⠦' '⠧' '⠇' '⠏')
# If colors are not defined yet or causing issues, remove them for debugging
# local blue_color="$BLUE"
# local green_color="$GREEN"
# local nc_color="$NC"
local blue_color='\033[0;34m' # Define locally if not sure about global scope yet
local green_color='\033[1;32m'
local nc_color='\033[0m'
local frame_count=${#spin_frames[@]}
local i=0
# Hide cursor
tput civis 2>/dev/null || true
# Check if PID is valid and running
while kill -0 "$pid" 2>/dev/null; do
# Ensure message is not empty
local display_message="${message:-Processing}"
printf "\r${blue_color}%s %s${nc_color} " "$display_message" "${spin_frames[$i]}"
i=$(((i + 1) % frame_count))
sleep 0.08
done
# Show checkmark and restore cursor
# Ensure message is not empty for the final display
local final_display_message="${message:-Done}"
printf "\r${blue_color}%s ${green_color}✔${nc_color}\n" "$final_display_message"
tput cnorm 2>/dev/null || true
}
execute_with_loading() {
local command="$1"
local message="$2"
log_message "Executing: $command"
# Make eval safer by ensuring command is not empty
if [[ -z "$command" ]]; then
print_error "execute_with_loading received an empty command for message: $message"
return 1 # Or exit, depending on desired strictness
fi
eval "$command" >>"$LOG_FILE" 2>&1 &
local pid=$!
show_loading $pid "$message"
wait $pid
local exit_code=$?
if [ $exit_code -ne 0 ]; then
print_error "Command failed (exit code $exit_code): $command" # Added exit code
print_error "Check log file: $LOG_FILE"
# Consider not exiting here directly but returning the error,
# letting the caller decide, or rely on the ERR trap.
return $exit_code # MODIFIED FROM exit $exit_code
fi
return $exit_code
}
execute_as_www_data() {
local command_to_execute="$1"
local loading_message="$2"
local actual_command_string
if id "www-data" &>/dev/null; then
if command -v sudo &>/dev/null; then
actual_command_string="sudo -u www-data $command_to_execute"
execute_with_loading "$actual_command_string" "$loading_message (as www-data via sudo)"
elif [[ $EUID -eq 0 ]]; then # Already root, use su
# Ensure command_to_execute is properly quoted for su -c
# Basic quoting for simple commands; complex commands might need more care
local escaped_command_to_execute=$(printf "%q" "$command_to_execute")
if [[ "$command_to_execute" == *\;* || "$command_to_execute" == *\|\|* || "$command_to_execute" == *\&\&* ]]; then
# For complex commands, wrap in sh -c if not already
if [[ ! ("$command_to_execute" == sh\ -c\ *) && ! ("$command_to_execute" == bash\ -c\ *) ]]; then
escaped_command_to_execute=$(printf "sh -c %q" "$command_to_execute")
fi
fi
actual_command_string="su -s /bin/bash -c $escaped_command_to_execute www-data"
execute_with_loading "$actual_command_string" "$loading_message (as www-data via su)"
else
print_warning "Cannot switch to www-data: sudo not found and not root. Running as current user."
execute_with_loading "$command_to_execute" "$loading_message (as current user)"
fi
else
print_warning "User www-data not found. Running as current user. Check permissions later."
execute_with_loading "$command_to_execute" "$loading_message (as current user)"
fi
return $? # Return the exit code from execute_with_loading
}
print_banner() {
# Make clear command more fault-tolerant
command clear 2>/dev/null || printf '\033c' || echo "--- Attempted to clear screen ---"
print_color $CYAN "
╔══════════════════════════════════════════════════════════════╗
║ ║
║ ${BOLD}${WHITE}██████╗ ███████╗███████╗███████╗██████╗ ██╗ ██╗${NC}${CYAN} ║
║ ${BOLD}${WHITE}██╔══██╗██╔════╝╚══███╔╝██╔════╝██╔══██╗╚██╗██╔╝${NC}${CYAN} ║
║ ${BOLD}${WHITE}██║ ██║█████╗ ███╔╝ █████╗ ██████╔╝ ╚███╔╝ ${NC}${CYAN} ║
║ ${BOLD}${WHITE}██║ ██║██╔══╝ ███╔╝ ██╔══╝ ██╔══██╗ ██╔██╗ ${NC}${CYAN} ║
║ ${BOLD}${WHITE}██████╔╝███████╗███████╗███████╗██║ ██║██╔╝ ██╗${NC}${CYAN} ║
║ ${BOLD}${WHITE}╚═════╝ ╚══════╝╚══════╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝${NC}${CYAN} ║
║ ║
║ ${BOLD}${YELLOW}INSTALLATION & UPDATE SCRIPT v${SCRIPT_VERSION}${NC}${CYAN} ║
║ 🚀 Requires Root Access 🚀 ║
╚══════════════════════════════════════════════════════════════╝
"
print_color $YELLOW "📋 This script can install or update DezerX on Debian systems"
print_color $YELLOW "⚡ Estimated time: 3-6 minutes (install) / 1-3 minutes (update)"
print_color $YELLOW "📝 Operation log: $LOG_FILE"
echo ""
}
print_step() {
echo ""
print_color $BOLD "${CYAN}┌─────────────────────────────────────────────────────────────┐"
local step_line="│ Step $1: $2"
local pad_length=$((62 - ${#step_line}))
printf -v pad '%*s' "$pad_length" ''
print_color $BOLD "${CYAN}${step_line}${pad}│"
print_color $BOLD "${CYAN}└─────────────────────────────────────────────────────────────┘"
}
print_success() {
printf "${GREEN}✔ %s${NC}\n" "$1"
}
print_error() {
print_color $RED "❌ $1"
}
print_info() {
print_color $BLUE "ℹ️ $1"
}
print_warning() {
print_color $YELLOW "⚠️ $1"
}
check_root() {
if [[ $EUID -ne 0 ]]; then
print_error "This script must be run as root!"
print_info "Please run: sudo $0"
exit 1
fi
print_success "Running with root privileges"
}
choose_install_variant() {
print_step "0" "CHOOSE INSTALLATION VARIANT"
print_color $CYAN "Please choose the installation variant:"
print_color $WHITE "1) 🆕 Normal (without a GUI)"
print_color $WHITE "2) 🖥️ GUI (with a graphical interface) (ALPHA) (not tested with Debian)"
echo ""
while true; do
print_color $WHITE "Please choose an option (1 or 2):"
read -r choice
case $choice in
1)
print_success "Selected: Normal Installation (without GUI)"
return 0
;;
2)
print_success "Selected: GUI Installation (ALPHA)"
print_warning "This variant is still in ALPHA stage and may not work as expected."
# Download and run the GUI script, then exit this script
curl -fsSL https://raw.githubusercontent.com/Dezer-Host/script/main/script_gui.sh -o /tmp/dx.sh && bash /tmp/dx.sh
exit 0
;;
*)
print_error "Invalid choice. Please enter 1 or 2."
;;
esac
done
}
choose_operation_mode() {
print_step "1" "CHOOSE OPERATION"
print_color $CYAN "What would you like to do?"
print_color $WHITE "1) 🆕 Fresh Installation - Install DezerX from scratch"
print_color $WHITE "2) 🔄 Update Existing - Update an existing DezerX installation"
print_color $WHITE "3) ⚠️ Delete Installation - Remove DezerX and all its data ⚠️"
echo ""
while true; do
print_color $WHITE "Please choose an option (1, 2, or 3):"
read -r choice
case $choice in
1)
OPERATION_MODE="install"
print_success "Selected: Fresh Installation"
print_warning "The non-automatic restore feature is intended for developers and testing environments only."
print_color $WHITE "Would you like to automatically restore the previous backup if an error occurs? (y/n):"
read -r restore_choice
case $restore_choice in
[Yy] | [Yy][Ee][Ss])
print_info "Automatic restore enabled"
RESTORE_ON_FAILURE="yes"
;;
[Nn] | [Nn][Oo])
print_info "Automatic restore disabled"
RESTORE_ON_FAILURE="no"
;;
*)
print_error "Invalid choice. Defaulting to automatic restore."
RESTORE_ON_FAILURE="yes"
;;
esac
break
;;
2)
OPERATION_MODE="update"
print_success "Selected: Update Existing Installation"
print_warning "The non-automatic restore feature is intended for developers and testing environments only."
print_color $WHITE "Would you like to automatically restore the previous backup if an error occurs? (y/n):"
read -r restore_choice
case $restore_choice in
[Yy] | [Yy][Ee][Ss])
print_info "Automatic restore enabled"
RESTORE_ON_FAILURE="yes"
;;
[Nn] | [Nn][Oo])
print_info "Automatic restore disabled"
RESTORE_ON_FAILURE="no"
;;
*)
print_error "Invalid choice. Defaulting to automatic restore."
RESTORE_ON_FAILURE="yes"
;;
esac
break
;;
3)
OPERATION_MODE="delete"
print_success "Selected: Delete Installation"
print_warning "This will remove DezerX and all its data permanently!"
print_color $WHITE "Are you sure you want to delete the installation? Type 'DELETE EVERYTHING' to confirm:"
read -r confirm_delete
if [[ "$confirm_delete" == "DELETE EVERYTHING" ]]; then
print_info "Proceeding with deletion..."
local deletion_error=0
# Ask for installation directory
print_color $WHITE "Enter the DezerX installation directory to delete [default: /var/www/DezerX]:"
read -r INSTALL_DIR_DELETE
if [[ -z "$INSTALL_DIR_DELETE" ]]; then
INSTALL_DIR_DELETE="/var/www/DezerX"
fi
local env_file_path_delete="$INSTALL_DIR_DELETE/.env"
local DB_FULL_NAME_DELETE=""
local DB_USER_FULL_DELETE=""
if [[ -f "$env_file_path_delete" ]]; then
DB_FULL_NAME_DELETE=$(get_env_variable "DB_DATABASE" "$env_file_path_delete")
DB_USER_FULL_DELETE=$(get_env_variable "DB_USERNAME" "$env_file_path_delete")
else
print_warning ".env file not found at $env_file_path_delete. Will ask for DB details if cleanup is desired."
print_color $WHITE "Do you want to attempt to manually specify and delete database/user? (y/n)"
read -r manual_db_delete
if [[ "$manual_db_delete" =~ ^[Yy]$ ]]; then
print_color $WHITE "Enter database name to delete (leave blank if none):"
read -r DB_FULL_NAME_DELETE
print_color $WHITE "Enter database user to delete (leave blank if none):"
read -r DB_USER_FULL_DELETE
fi
fi
print_info "Removing Nginx configuration..."
if [[ -f /etc/nginx/sites-enabled/dezerx.conf ]]; then
rm -f /etc/nginx/sites-enabled/dezerx.conf >>"$LOG_FILE" 2>&1 || deletion_error=1
fi
if [[ -f /etc/nginx/sites-available/dezerx.conf ]]; then
rm -f /etc/nginx/sites-available/dezerx.conf >>"$LOG_FILE" 2>&1 || deletion_error=1
fi
systemctl reload nginx >>"$LOG_FILE" 2>&1 || deletion_error=1
print_success "Nginx configuration removed."
print_info "Removing installation directory..."
if [[ -d "$INSTALL_DIR_DELETE" ]]; then
rm -rf "$INSTALL_DIR_DELETE" >>"$LOG_FILE" 2>&1 || deletion_error=1
print_success "Installation directory removed: $INSTALL_DIR_DELETE"
else
print_warning "Directory $INSTALL_DIR_DELETE does not exist. Skipping directory removal."
fi
if command -v mariadb &>/dev/null; then
if [[ -n "$DB_FULL_NAME_DELETE" ]]; then
print_info "Removing database '$DB_FULL_NAME_DELETE'..."
mariadb -e "DROP DATABASE IF EXISTS \`$DB_FULL_NAME_DELETE\`;" >>"$LOG_FILE" 2>&1 || deletion_error=1
print_success "Database '$DB_FULL_NAME_DELETE' removed (if it existed)."
fi
if [[ -n "$DB_USER_FULL_DELETE" ]]; then
print_info "Removing database user '$DB_USER_FULL_DELETE'..."
mariadb -e "DROP USER IF EXISTS '$DB_USER_FULL_DELETE'@'127.0.0.1';" >>"$LOG_FILE" 2>&1 || deletion_error=1
mariadb -e "DROP USER IF EXISTS '$DB_USER_FULL_DELETE'@'localhost';" >>"$LOG_FILE" 2>&1 || deletion_error=1
print_success "Database user '$DB_USER_FULL_DELETE' removed (if it existed)."
fi
if [[ -n "$DB_FULL_NAME_DELETE" || -n "$DB_USER_FULL_DELETE" ]]; then
mariadb -e "FLUSH PRIVILEGES;" >>"$LOG_FILE" 2>&1 || deletion_error=1
fi
else
print_warning "mariadb command not found. Skipping database and user removal."
fi
print_info "Removing queue worker service..."
if systemctl is-active --quiet dezerx.service; then
systemctl stop dezerx.service >>"$LOG_FILE" 2>&1 || deletion_error=1
fi
if systemctl is-enabled --quiet dezerx.service; then
systemctl disable dezerx.service >>"$LOG_FILE" 2>&1 || deletion_error=1
fi
if [[ -f /etc/systemd/system/dezerx.service ]]; then
rm -f /etc/systemd/system/dezerx.service >>"$LOG_FILE" 2>&1 || deletion_error=1
fi
systemctl daemon-reload >>"$LOG_FILE" 2>&1 || deletion_error=1
print_success "Queue worker service removed."
if [[ "$deletion_error" -ne 0 ]]; then
print_error "Some errors occurred during deletion. Please check the log: $LOG_FILE"
else
print_success "DezerX and all related data have been deleted."
fi
exit 0
else
print_info "Deletion cancelled by user"
exit 0
fi
break # Should not be reached if deletion proceeds or is cancelled
;;
*)
print_error "Invalid choice. Please enter 1, 2, or 3."
;;
esac
done
}
check_system_requirements() {
if [[ "$OPERATION_MODE" == "install" ]]; then
print_step "2" "CHECKING SYSTEM REQUIREMENTS"
else
print_step "2" "CHECKING SYSTEM STATUS"
fi
if ! command -v curl &>/dev/null; then
execute_with_loading "apt-get update && apt-get install -y curl" "Installing curl"
fi
if ! command -v unzip &>/dev/null; then
execute_with_loading "apt-get install -y unzip" "Installing unzip"
fi
if ! command -v lsb_release &>/dev/null; then
execute_with_loading "apt-get install -y lsb-release" "Installing lsb-release"
fi
local os_name=$(lsb_release -si)
local os_version=$(lsb_release -sr)
print_info "Operating System: $os_name $os_version"
if [[ "$os_name" != "Debian" ]]; then
print_error "This script only supports Debian GNU/Linux."
print_info "Your OS: $os_name $os_version"
exit 1
fi
local available_space=$(df / | awk 'NR==2 {print $4}') # Space in 1K blocks
local required_space_kb # Required space in 1K blocks
if [[ "$OPERATION_MODE" == "install" ]]; then
required_space_kb=$((5 * 1024 * 1024)) # 5GB in KB
else
required_space_kb=$((2 * 1024 * 1024)) # 2GB in KB
fi
if [[ $available_space -lt $required_space_kb ]]; then
print_error "Insufficient disk space. Required: $((required_space_kb / 1024 / 1024))GB, Available: $((available_space / 1024 / 1024))GB"
exit 1
fi
local total_mem_mb=$(free -m | awk 'NR==2{print $2}')
if [[ $total_mem_mb -lt 1000 ]]; then # Check for ~1GB
print_warning "Low memory detected: ${total_mem_mb}MB. Recommended: 2GB (2048MB) or more."
fi
print_success "System requirements check passed"
}
validate_domain() {
local domain_to_validate=$1 # Renamed to avoid conflict with global DOMAIN
if [[ $domain_to_validate =~ ^https?:// ]]; then
return 2 # Indicates protocol included
fi
# Basic domain regex: starts with letter/number, can contain letters, numbers, hyphens (not at start/end of a part)
# and must have at least one dot for TLD.
if [[ ! $domain_to_validate =~ ^[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)+$ ]]; then
return 1 # Invalid format
fi
return 0 # Valid
}
validate_directory() {
local dir_to_validate=$1 # Renamed to avoid conflict
# Must be an absolute path, basic character set
if [[ ! $dir_to_validate =~ ^/[a-zA-Z0-9/._-]+$ ]]; then
return 1
fi
return 0
}
get_install_input() {
print_step "3" "COLLECTING INSTALLATION DETAILS"
while true; do
print_color $BOLD$WHITE "🔑 Enter your DezerX license key:"
read -r LICENSE_KEY
if [[ -n "$LICENSE_KEY" && ${#LICENSE_KEY} -ge 10 ]]; then
break
else
print_error "License key must be at least 10 characters. Please try again."
fi
done
while true; do
print_color $WHITE "🌐 Enter your domain or subdomain (e.g., example.com or app.example.com):"
print_color $WHITE " ⚠️ Do NOT include http:// or https:// - just the domain name"
read -r DOMAIN
local validation_result
validate_domain "$DOMAIN"
validation_result=$?
if [[ $validation_result -eq 2 ]]; then
print_error "Please enter the domain WITHOUT http:// or https://"
print_error "Example: Use 'example.com' instead of 'https://example.com'"
continue
elif [[ $validation_result -eq 1 ]]; then
print_error "Invalid domain format. Please try again."
continue
else
break
fi
done
while true; do
print_color $WHITE "🌐 Use HTTPS (recommended) or HTTP? [https/http, default: https]:"
read -r protocol_choice
if [[ -z "$protocol_choice" || "$protocol_choice" =~ ^[Hh][Tt][Tt][Pp][Ss]$ ]]; then
PROTOCOL="https"
break
elif [[ "$protocol_choice" =~ ^[Hh][Tt][Tt][Pp]$ ]]; then
PROTOCOL="http"
break
else
print_error "Please enter 'https' or 'http'."
fi
done
while true; do
print_color $WHITE "📁 Enter installation directory [default: /var/www/DezerX]:"
read -r INSTALL_DIR
if [[ -z "$INSTALL_DIR" ]]; then
INSTALL_DIR="/var/www/DezerX"
fi
if validate_directory "$INSTALL_DIR"; then
break
else
print_error "Invalid directory path. Path must be absolute (e.g., /var/www/myapp). Please try again."
fi
done
while true; do
print_color $CYAN "🗄️ DATABASE CONFIGURATION:"
print_color $WHITE "Leave blank to use defaults."
if [[ -z "$DB_NAME_PREFIX" ]]; then
DB_NAME_PREFIX=$(echo "$DOMAIN" | grep -o '^[a-zA-Z0-9]*' | tr '[:upper:]' '[:lower:]' | cut -c1-4)
if [[ -z "$DB_NAME_PREFIX" ]]; then
DB_NAME_PREFIX="dzrx"
fi
fi
print_color $WHITE "Database name [default: ${DB_NAME_PREFIX}_dezerx]:"
read -r user_db_name
if [[ -n "$user_db_name" ]]; then
DB_FULL_NAME="$user_db_name"
else
DB_FULL_NAME="${DB_NAME_PREFIX}_dezerx"
fi
print_color $WHITE "Database user [default: ${DB_NAME_PREFIX}_dezer]:"
read -r user_db_user
if [[ -n "$user_db_user" ]]; then
DB_USER_FULL="$user_db_user"
else
DB_USER_FULL="${DB_NAME_PREFIX}_dezer"
fi
print_color $WHITE "Database password [leave blank to auto-generate]:"
read -r -s user_db_pass # -s for silent input
echo # Newline after silent input
if [[ -n "$user_db_pass" ]]; then
DB_PASSWORD="$user_db_pass"
else
if [[ -z "$DB_PASSWORD" ]]; then # Generate only if not already set (e.g. by update)
DB_PASSWORD=$(openssl rand -base64 32 | tr -d "=+/\\\\" | cut -c1-25)
fi
fi
break
done
echo ""
print_color $CYAN "📋 INSTALLATION SUMMARY:"
print_info "License Key: ${LICENSE_KEY:0:8}***"
print_info "Domain: $DOMAIN"
print_info "Full URL: ${PROTOCOL}://$DOMAIN"
print_info "Install Directory: $INSTALL_DIR"
print_info "Database Name: $DB_FULL_NAME"
print_info "Database User: $DB_USER_FULL"
print_info "Database Password: [${DB_PASSWORD:+Generated/Set}]"
echo ""
while true; do
print_color $WHITE "Continue with installation? (y/n):"
read -r confirm
case $confirm in
[Yy] | [Yy][Ee][Ss])
break
;;
[Nn] | [Nn][Oo])
print_info "Installation cancelled by user"
exit 0
;;
*)
print_error "Please answer with y/yes or n/no"
;;
esac
done
print_success "Configuration confirmed!"
}
get_update_input() {
print_step "3" "COLLECTING UPDATE DETAILS"
while true; do
print_color $BOLD$WHITE "🔑 Enter your DezerX license key:"
read -r LICENSE_KEY
if [[ -n "$LICENSE_KEY" && ${#LICENSE_KEY} -ge 10 ]]; then
break
else
print_error "License key must be at least 10 characters. Please try again."
fi
done
while true; do
print_color $WHITE "🌐 Enter your domain (e.g., example.com or app.example.com):"
print_color $WHITE " ⚠️ Do NOT include http:// or https:// - just the domain name"
read -r DOMAIN
local validation_result
validate_domain "$DOMAIN"
validation_result=$?
if [[ $validation_result -eq 2 ]]; then
print_error "Please enter the domain WITHOUT http:// or https://"
print_error "Example: Use 'example.com' instead of 'https://example.com'"
continue
elif [[ $validation_result -eq 1 ]]; then
print_error "Invalid domain format. Please try again."
continue
else
break
fi
done
while true; do
print_color $WHITE "🌐 Use HTTPS (recommended) or HTTP? [https/http, default: https]:"
read -r protocol_choice
if [[ -z "$protocol_choice" || "$protocol_choice" =~ ^[Hh][Tt][Tt][Pp][Ss]$ ]]; then
PROTOCOL="https"
break
elif [[ "$protocol_choice" =~ ^[Hh][Tt][Tt][Pp]$ ]]; then
PROTOCOL="http"
break
else
print_error "Please enter 'https' or 'http'."
fi
done
while true; do
print_color $WHITE "📁 Enter your existing DezerX directory [default: /var/www/DezerX]:"
read -r INSTALL_DIR
if [[ -z "$INSTALL_DIR" ]]; then
INSTALL_DIR="/var/www/DezerX"
fi
if [[ ! -d "$INSTALL_DIR" ]]; then
print_error "Directory $INSTALL_DIR does not exist. Please check the path."
continue
fi
if [[ ! -f "$INSTALL_DIR/.env" ]]; then
print_error "No .env file found in $INSTALL_DIR. This doesn't appear to be a DezerX installation."
continue
fi
if [[ ! -f "$INSTALL_DIR/artisan" ]]; then
print_error "No artisan file found in $INSTALL_DIR. This doesn't appear to be a Laravel/DezerX installation."
continue
fi
DB_FULL_NAME=$(get_env_variable "DB_DATABASE" "$INSTALL_DIR/.env")
DB_USER_FULL=$(get_env_variable "DB_USERNAME" "$INSTALL_DIR/.env")
DB_PASSWORD=$(get_env_variable "DB_PASSWORD" "$INSTALL_DIR/.env")
if [[ -z "$DB_FULL_NAME" ]]; then
DB_FULL_NAME="dezerx"
print_warning "DB_DATABASE not found in .env, using default 'dezerx'"
fi
if [[ -z "$DB_USER_FULL" ]]; then
DB_USER_FULL="dezer"
print_warning "DB_USERNAME not found in .env, using default 'dezer'"
fi
# DB_PASSWORD can be empty if not set or if user wants to re-enter, handle accordingly
break
done
print_success "Found existing DezerX installation at: $INSTALL_DIR"
echo ""
print_color $CYAN "📋 UPDATE SUMMARY:"
print_info "License Key: ${LICENSE_KEY:0:8}***"
print_info "Domain: $DOMAIN"
print_info "Full URL: ${PROTOCOL}://$DOMAIN"
print_info "Existing Directory: $INSTALL_DIR"
echo ""
while true; do
print_color $WHITE "Continue with update? (y/n):"
read -r confirm
case $confirm in
[Yy] | [Yy][Ee][Ss])
break
;;
[Nn] | [Nn][Oo])
print_info "Update cancelled by user"
exit 0
;;
*)
print_error "Please answer with y/yes or n/no"
;;
esac
done
print_success "Update configuration confirmed!"
}
verify_license() {
if [[ "$OPERATION_MODE" == "install" ]]; then
print_step "4" "VERIFYING LICENSE"
else
print_step "4" "VERIFYING LICENSE" # Update also needs license verification
fi
print_info "Contacting DezerX license server..."
local temp_file
temp_file=$(mktemp)
local http_code
# Ensure curl uses a reasonable timeout
http_code=$(curl -s -w "%{http_code}" -X POST \
-H "Authorization: Bearer $LICENSE_KEY" \
-H "domain: $DOMAIN" \
-H "product: 1" \
-H "Content-Type: application/json" \
-o "$temp_file" \
--connect-timeout 30 \
--max-time 60 \
https://market.dezerx.com/api/v1/verify)
if [[ "$http_code" == "200" ]]; then
print_success "License verified successfully!"
rm -f "$temp_file"
return 0
else
print_error "License verification failed (HTTP Code: $http_code)"
if [[ -f "$temp_file" ]]; then
local error_msg
error_msg=$(cat "$temp_file" 2>/dev/null || echo "Unknown error from server")
print_error "Server response: $error_msg"
rm -f "$temp_file"
fi
print_error "Please check your license key and domain, then try again."
exit 1
fi
}
create_backup() {
# This function is only relevant for update mode
if [[ "$OPERATION_MODE" != "update" ]]; then
return 0
fi
print_step "5" "CREATING BACKUP OF EXISTING INSTALLATION"
BACKUP_DIR="/tmp/dezerx-backup-$(date +%Y%m%d-%H%M%S)"
print_info "Backup location: $BACKUP_DIR"
# Ensure INSTALL_DIR is set
if [[ -z "$INSTALL_DIR" || ! -d "$INSTALL_DIR" ]]; then
print_error "Installation directory '$INSTALL_DIR' not found or not set. Cannot create backup."
exit 1
fi
execute_with_loading "cp -a \"$INSTALL_DIR\" \"$BACKUP_DIR\"" "Creating backup of $INSTALL_DIR"
if [[ ! -f "$BACKUP_DIR/.env" ]]; then
print_error "Backup verification failed - .env file not found in backup directory: $BACKUP_DIR"
# Decide if this is fatal or a warning. For safety, let's make it fatal.
exit 1
fi
print_success "Application files backup created successfully!"
print_info "💾 Backup saved to: $BACKUP_DIR"
}
get_env_variable() {
local var_name="$1"
local env_file="$2"
local value=""
if [[ -f "$env_file" ]]; then
# Read variable:
# 1. Grep the line starting with VAR_NAME=
# 2. Cut everything after the first '='
# 3. Remove leading/trailing whitespace from the value.
# 4. Remove surrounding quotes (single or double) if present.
# 5. Remove inline comments (starting with a space then '#').
# 6. Remove DOS carriage return.
value=$(grep "^${var_name}=" "$env_file" | tail -n 1 | cut -d '=' -f 2- |
sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' \
-e 's/^"\(.*\)"$/\1/' -e "s/^'\(.*\)'$/\1/" \
-e 's/[[:space:]]*#.*$//' -e 's/[[:space:]]*$//' \
-e 's/\r$//')
fi
echo "$value"
}
backup_database() {
if [[ "$OPERATION_MODE" != "update" ]]; then
return 0
fi
print_step "5.1" "BACKING UP DATABASE"
local env_file="$INSTALL_DIR/.env" # Use current INSTALL_DIR for .env
if [[ ! -f "$env_file" ]]; then
print_warning ".env file not found at $env_file. Skipping database backup."
return 0
fi
local db_connection db_host db_port db_database db_username db_password_env
db_connection=$(get_env_variable "DB_CONNECTION" "$env_file")
db_host=$(get_env_variable "DB_HOST" "$env_file")
db_port=$(get_env_variable "DB_PORT" "$env_file")
db_database=$(get_env_variable "DB_DATABASE" "$env_file") # This is DB_FULL_NAME
db_username=$(get_env_variable "DB_USERNAME" "$env_file") # This is DB_USER_FULL
db_password_env=$(get_env_variable "DB_PASSWORD" "$env_file") # This is DB_PASSWORD
if [[ "$db_connection" != "mysql" ]]; then
print_warning "Database connection is not 'mysql' in .env (found: '$db_connection'). Skipping database backup."
return 0
fi
if [[ -z "$db_host" || -z "$db_database" || -z "$db_username" ]]; then
print_error "Missing critical database credentials (host, database, or username) in .env file. Cannot perform database backup."
# This is critical, so we should probably exit or make it very clear.
# For now, let's return 1 to indicate failure.
return 1
fi
# Use existing BACKUP_DIR from create_backup()
if [[ -z "$BACKUP_DIR" || ! -d "$BACKUP_DIR" ]]; then
print_error "BACKUP_DIR '$BACKUP_DIR' not set or not a directory. create_backup() should run first."
return 1
fi
DB_BACKUP_FILE="$BACKUP_DIR/database_$(date +%Y%m%d-%H%M%S).sql.gz"
print_info "Backing up database '$db_database'..."
print_info "Backup file: $DB_BACKUP_FILE"
local port_arg=""
if [[ -n "$db_port" ]]; then
port_arg="--port=$db_port"
fi
# Temporarily set MYSQL_PWD for mysqldump
export MYSQL_PWD="$db_password_env"
local mysqldump_cmd="mysqldump --host=$db_host $port_arg --user=$db_username $db_database | gzip > \"$DB_BACKUP_FILE\""
if ! command -v mysqldump &>/dev/null; then
print_error "mysqldump command not found. Cannot perform database backup."
unset MYSQL_PWD
return 1
fi
# Use execute_with_loading for this potentially long operation
execute_with_loading "$mysqldump_cmd" "Creating database backup"
local dump_exit_code=$? # Get exit code from execute_with_loading's wait
unset MYSQL_PWD # Always unset password
if [ $dump_exit_code -ne 0 ]; then
print_error "Database backup failed! (mysqldump exit code: $dump_exit_code)"
rm -f "$DB_BACKUP_FILE" # Clean up failed backup file
return 1
fi
if [[ ! -s "$DB_BACKUP_FILE" ]]; then # Check if file exists and is not empty
print_error "Database backup file is empty or was not created: $DB_BACKUP_FILE"
return 1
fi
print_success "Database backup completed successfully!"
print_info "Database backup saved to: $DB_BACKUP_FILE"
return 0
}
restore_database() {
if [[ "$OPERATION_MODE" != "update" || "$RESTORE_ON_FAILURE" != "yes" ]]; then
return 0
fi
print_info "Attempting to restore database from backup..."
if [[ -z "$DB_BACKUP_FILE" || ! -f "$DB_BACKUP_FILE" ]]; then
print_warning "No database backup file found ($DB_BACKUP_FILE) or specified. Skipping database restore."
return 1
fi
local env_file="$INSTALL_DIR/.env" # Use INSTALL_DIR which should now point to the restored app files
if [[ ! -f "$env_file" ]]; then
# If .env is not in restored app files, try backup dir .env
env_file="$BACKUP_DIR/.env"
fi
if [[ ! -f "$env_file" ]]; then
print_error ".env file not found in $INSTALL_DIR or $BACKUP_DIR. Cannot determine database credentials for restore."
return 1
fi
local db_host db_port db_database db_username db_password_env
db_host=$(get_env_variable "DB_HOST" "$env_file")
db_port=$(get_env_variable "DB_PORT" "$env_file")
db_database=$(get_env_variable "DB_DATABASE" "$env_file")
db_username=$(get_env_variable "DB_USERNAME" "$env_file")
db_password_env=$(get_env_variable "DB_PASSWORD" "$env_file")
if [[ -z "$db_host" || -z "$db_database" || -z "$db_username" ]]; then
print_error "Missing database credentials in .env. Cannot restore database."
return 1
fi
print_info "Restoring database '$db_database' from $DB_BACKUP_FILE..."
local port_arg=""
if [[ -n "$db_port" ]]; then
port_arg="--port=$db_port"
fi
export MYSQL_PWD="$db_password_env"
# Drop and recreate database before import to ensure clean state
mariadb --host="$db_host" $port_arg --user="$db_username" -e "DROP DATABASE IF EXISTS \`$db_database\`; CREATE DATABASE \`$db_database\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" >>"$LOG_FILE" 2>&1
local restore_cmd="gunzip < \"$DB_BACKUP_FILE\" | mariadb --host=$db_host $port_arg --user=$db_username $db_database"
execute_with_loading "$restore_cmd" "Restoring database content"
local restore_exit_code=$?
unset MYSQL_PWD
if [ $restore_exit_code -ne 0 ]; then
print_error "Database restore failed! (Exit code: $restore_exit_code)"
return 1
fi
print_success "Database restored successfully from $DB_BACKUP_FILE."
return 0
}
restore_backup() {
# This function is only relevant for update mode if RESTORE_ON_FAILURE is yes
if [[ "$OPERATION_MODE" != "update" || "$RESTORE_ON_FAILURE" != "yes" ]]; then
return 0
fi
print_error "Attempting to restore application files from backup due to failure..."
if [[ -n "$BACKUP_DIR" && -d "$BACKUP_DIR" ]]; then
print_info "Removing potentially failed/incomplete update files from $INSTALL_DIR..."
rm -rf "$INSTALL_DIR"/* "$INSTALL_DIR"/.[^.]* 2>/dev/null || true # Clean target
mkdir -p "$INSTALL_DIR" # Ensure target dir exists
print_info "Restoring application files from backup: $BACKUP_DIR to $INSTALL_DIR"
# Use cp -a for preserving attributes, then rsync for safety if cp fails partially
if cp -a "$BACKUP_DIR"/* "$INSTALL_DIR"/ && cp -a "$BACKUP_DIR"/.[^.]* "$INSTALL_DIR"/ 2>/dev/null; then
: # cp successful
else
# Fallback to rsync if cp had issues (e.g. with hidden files)
rsync -a --delete "$BACKUP_DIR/" "$INSTALL_DIR/" >>"$LOG_FILE" 2>&1
fi
print_info "Setting proper permissions after file restore..."
# Ensure www-data exists or use a fallback if necessary (though www-data is standard on Debian for Nginx/Apache)
if id "www-data" &>/dev/null; then
chown -R www-data:www-data "$INSTALL_DIR" >>"$LOG_FILE" 2>&1
else
print_warning "User www-data not found. Skipping chown for restored files."
fi
chmod -R 755 "$INSTALL_DIR" >>"$LOG_FILE" 2>&1
chmod -R 775 "$INSTALL_DIR/storage" 2>/dev/null || true
chmod -R 775 "$INSTALL_DIR/bootstrap/cache" 2>/dev/null || true
print_success "Application files backup restored successfully to $INSTALL_DIR!"
print_info "Your original application files should be restored."
else
print_error "No backup directory found ($BACKUP_DIR) or it's not a directory. Cannot restore application files."
return 1 # Indicate failure