-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.sh
More file actions
2049 lines (1702 loc) · 71.3 KB
/
script.sh
File metadata and controls
2049 lines (1702 loc) · 71.3 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
# --- EARLY SYSTEM CHECK: Redirect Debian users to the Debian script ---
if [ -f /etc/debian_version ] && ! grep -qi ubuntu /etc/os-release; then
echo "Detected Debian system. Redirecting to the DezerX Debian installer..."
curl -fsSL https://raw.githubusercontent.com/Dezer-Host/script/main/script_debian.sh -o /tmp/dx.sh && bash /tmp/dx.sh
exit 0
fi
set -euo pipefail
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"
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="/tmp/dezerx-install.log"
OPERATION_MODE=""
BACKUP_DIR=""
DB_BACKUP_FILE=""
RESTORE_ON_FAILURE=""
PROTOCOL="https"
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."
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=('⠋' '⠙' '⠹' '⠸' '⠼' '⠴' '⠦' '⠧' '⠇' '⠏')
local frame_count=${#spin_frames[@]}
local i=0
# Hide cursor
tput civis 2>/dev/null || true
while kill -0 "$pid" 2>/dev/null; do
printf "\r${BLUE}%s %s${NC} " "$message" "${spin_frames[$i]}"
i=$(((i + 1) % frame_count))
sleep 0.08
done
# Show checkmark and restore cursor
printf "\r${BLUE}%s ${GREEN}✔${NC}\n" "$message"
tput cnorm 2>/dev/null || true
}
execute_with_loading() {
local command="$1"
local message="$2"
log_message "Executing: $command"
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: $command"
print_error "Check log file: $LOG_FILE"
exit $exit_code
fi
return $exit_code
}
print_banner() {
clear
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"
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)"
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 or 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 or 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" != "Ubuntu" ]] && [[ "$os_name" != "Debian" ]]; then
print_error "This script only supports Ubuntu and Debian"
exit 1
fi
local available_space=$(df / | awk 'NR==2 {print $4}')
local required_space
if [[ "$OPERATION_MODE" == "install" ]]; then
required_space=5242880
else
required_space=2097152
fi
if [[ $available_space -lt $required_space ]]; then
print_error "Insufficient disk space. Required: $((required_space / 1024 / 1024))GB, Available: $((available_space / 1024 / 1024))GB"
exit 1
fi
local total_mem=$(free -m | awk 'NR==2{print $2}')
if [[ $total_mem -lt 1024 ]]; then
print_warning "Low memory detected: ${total_mem}MB. Recommended: 2GB+"
fi
print_success "System requirements check passed"
}
validate_domain() {
local domain=$1
if [[ $domain =~ ^https?:// ]]; then
return 2
fi
if [[ ! $domain =~ ^[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
fi
return 0
}
validate_directory() {
local dir=$1
if [[ ! $dir =~ ^/[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. 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-Z]*' | 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
echo
if [[ -n "$user_db_pass" ]]; then
DB_PASSWORD="$user_db_pass"
else
if [[ -z "$DB_PASSWORD" ]]; then
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"
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
# --- NEU: DB-Infos aus .env lesen ---
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")
# Fallback, falls leer:
if [[ -z "$DB_FULL_NAME" ]]; then DB_FULL_NAME="dezerx"; fi
if [[ -z "$DB_USER_FULL" ]]; then DB_USER_FULL="dezer"; fi
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 "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"
fi
print_info "Contacting DezerX license server..."
local temp_file=$(mktemp)
local http_code
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: $http_code)"
if [[ -f "$temp_file" ]]; then
local error_msg=$(cat "$temp_file" 2>/dev/null || echo "Unknown error")
print_error "Server response: $error_msg"
rm -f "$temp_file"
fi
print_error "Please check your license key and domain."
exit 1
fi
}
create_backup() {
print_step "5" "CREATING BACKUP"
BACKUP_DIR="/tmp/dezerx-backup-$(date +%Y%m%d-%H%M%S)"
print_info "Creating full backup of existing installation..."
print_info "Backup location: $BACKUP_DIR"
execute_with_loading "cp -r $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"
exit 1
fi
print_success "Backup created successfully!"
print_info "💾 Backup saved to: $BACKUP_DIR"
}
get_env_variable() {
local var_name="$1"
local env_file="$2"
if [[ -f "$env_file" ]]; then
grep "^${var_name}=" "$env_file" | cut -d '=' -f 2- | sed 's/\r$//' | sed 's/"//g' | sed "s/'//g"
else
echo ""
fi
}
backup_database() {
print_step "5.1" "BACKING UP DATABASE"
local env_file="$INSTALL_DIR/.env"
if [[ ! -f "$env_file" ]]; then
print_warning ".env file not found at $env_file. Skipping database backup."
return 0 # This should return, not exit
fi
local db_connection=$(get_env_variable "DB_CONNECTION" "$env_file")
local db_host=$(get_env_variable "DB_HOST" "$env_file")
local db_port=$(get_env_variable "DB_PORT" "$env_file")
local db_database=$(get_env_variable "DB_DATABASE" "$env_file")
local db_username=$(get_env_variable "DB_USERNAME" "$env_file")
local db_password=$(get_env_variable "DB_PASSWORD" "$env_file")
if [[ "$db_connection" != "mysql" ]]; then
print_warning "Database connection is not 'mysql' in .env. Skipping database backup."
return 0 # This should return, not exit
fi
if [[ -z "$db_host" || -z "$db_database" || -z "$db_username" ]]; then
print_error "Missing database credentials in .env file. Cannot perform database backup."
exit 1 # Only exit on critical errors
fi
# Use existing BACKUP_DIR from create_backup()
if [[ -z "$BACKUP_DIR" ]]; then
print_error "BACKUP_DIR not set. create_backup() should run first."
exit 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="-P $db_port"
fi
export MYSQL_PWD="$db_password"
local mysqldump_cmd="mysqldump -h $db_host $port_arg -u $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
exit 1
fi
execute_with_loading "$mysqldump_cmd" "Creating database backup"
local exit_code=$?
unset MYSQL_PWD
if [ $exit_code -ne 0 ]; then
print_error "Database backup failed!"
return 1
fi
if [[ ! -s "$DB_BACKUP_FILE" ]]; then
print_error "Database backup file is empty or not created!"
return 1
fi
print_success "Database backup completed successfully!"
print_info "Database backup saved to: $DB_BACKUP_FILE"
# Add explicit continuation message
print_info "Continuing with update process..."
return 0
}
restore_backup() {
print_error "Restoring from backup due to update failure..."
if [[ -n "$BACKUP_DIR" && -d "$BACKUP_DIR" ]]; then
print_info "Removing failed update files..."
rm -rf "$INSTALL_DIR"
print_info "Restoring from backup: $BACKUP_DIR"
mv "$BACKUP_DIR" "$INSTALL_DIR"
print_info "Setting proper permissions after restore..."
chown -R www-data:www-data "$INSTALL_DIR"
chmod -R 755 "$INSTALL_DIR"
chmod -R 775 "$INSTALL_DIR/storage" 2>/dev/null || true
chmod -R 775 "$INSTALL_DIR/bootstrap/cache" 2>/dev/null || true
print_success "Backup restored successfully!"
print_info "Your original installation has been restored"
else
print_error "No backup found to restore from!"
fi
}
install_dependencies() {
print_step "5" "INSTALLING SYSTEM DEPENDENCIES"
execute_with_loading "apt-get update" "Updating package lists"
execute_with_loading "DEBIAN_FRONTEND=noninteractive apt-get upgrade -y" "Upgrading system packages"
execute_with_loading "apt-get install -y software-properties-common curl apt-transport-https ca-certificates gnupg lsb-release wget unzip git cron" "Installing basic dependencies"
print_info "Adding PHP repository..."
if ! LC_ALL=C.UTF-8 add-apt-repository -y ppa:ondrej/php >>"$LOG_FILE" 2>&1; then
print_warning "Failed to add PHP PPA, trying alternative method..."
fi
print_info "Adding Redis repository..."
curl -fsSL https://packages.redis.io/gpg | gpg --dearmor >/usr/share/keyrings/redis-archive-keyring.gpg 2>/dev/null
echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" >/etc/apt/sources.list.d/redis.list
print_info "Adding MariaDB repository..."
curl -LsS https://r.mariadb.com/downloads/mariadb_repo_setup | bash >>"$LOG_FILE" 2>&1
execute_with_loading "apt-get update" "Updating package lists with new repositories"
local packages="nginx php8.3 php8.3-common php8.3-cli php8.3-gd php8.3-mysql php8.3-mbstring php8.3-bcmath php8.3-xml php8.3-fpm php8.3-curl php8.3-zip mariadb-server tar unzip git redis-server ufw"
execute_with_loading "DEBIAN_FRONTEND=noninteractive apt-get install -y $packages" "Installing PHP, MariaDB, Nginx, and other dependencies"
execute_with_loading "systemctl start nginx && systemctl enable nginx" "Starting and enabling Nginx"
execute_with_loading "systemctl start php8.3-fpm && systemctl enable php8.3-fpm" "Starting and enabling PHP-FPM"
execute_with_loading "systemctl start redis-server && systemctl enable redis-server" "Starting and enabling Redis"
execute_with_loading "systemctl start cron && systemctl enable cron" "Starting and enabling Cron service"
execute_with_loading "systemctl stop ufw && systemctl disable ufw" "Stoping and disabling UFW due to later configuration"
execute_with_loading "mkdir -p /var/www" "Creating /var/www directory"
print_success "System dependencies installed successfully!"
}
install_composer() {
print_step "6" "INSTALLING COMPOSER"
local composer_installer="/tmp/composer-installer.php"
execute_with_loading "curl -sS https://getcomposer.org/installer -o $composer_installer" "Downloading Composer installer"
execute_with_loading "php $composer_installer --install-dir=/usr/local/bin --filename=composer" "Installing Composer"
rm -f "$composer_installer"
if ! command -v composer &>/dev/null; then
print_error "Composer installation failed"
exit 1
fi
print_success "Composer installed successfully!"
}
setup_database() {
print_step "7" "SETTING UP DATABASE"
execute_with_loading "systemctl start mariadb && systemctl enable mariadb" "Starting MariaDB service"
DB_PASSWORD=$(openssl rand -base64 32 | tr -d "=+/" | cut -c1-25)
print_info "Securing MariaDB installation and creating database/user..."
local sql_file=$(mktemp)
cat >"$sql_file" <<EOF
-- Create the dedicated database for the application
CREATE DATABASE IF NOT EXISTS \`$DB_FULL_NAME\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- Create the dedicated user for the application (both hosts!)
CREATE USER IF NOT EXISTS '$DB_USER_FULL'@'127.0.0.1' IDENTIFIED BY '$DB_PASSWORD';
CREATE USER IF NOT EXISTS '$DB_USER_FULL'@'localhost' IDENTIFIED BY '$DB_PASSWORD';
-- Grant all privileges on the application database to the user (both hosts!)
GRANT ALL PRIVILEGES ON \`$DB_FULL_NAME\`.* TO '$DB_USER_FULL'@'127.0.0.1' WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON \`$DB_FULL_NAME\`.* TO '$DB_USER_FULL'@'localhost' WITH GRANT OPTION;
-- Apply all privilege changes
FLUSH PRIVILEGES;
EOF
if ! mariadb <"$sql_file" >>"$LOG_FILE" 2>&1; then
print_error "Failed to secure MariaDB installation"
rm -f "$sql_file"
exit 1
fi
cat >"$sql_file" <<EOF
-- Create the dedicated database for the application
CREATE DATABASE IF NOT EXISTS \`$DB_FULL_NAME\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- Create the dedicated user for the application
CREATE USER IF NOT EXISTS '$DB_USER_FULL'@'127.0.0.1' IDENTIFIED BY '$DB_PASSWORD';
-- Grant all privileges on the application database to the user
GRANT ALL PRIVILEGES ON \`$DB_FULL_NAME\`.* TO '$DB_USER_FULL'@'127.0.0.1' WITH GRANT OPTION;
-- Apply all privilege changes
FLUSH PRIVILEGES;
EOF
if ! mariadb <"$sql_file" >>"$LOG_FILE" 2>&1; then
print_error "Failed to create database and user"
rm -f "$sql_file"
exit 1
fi
rm -f "$sql_file"
print_success "Database setup completed successfully!"
print_info "Database: $DB_FULL_NAME"
print_info "Username: $DB_USER_FULL"
print_info "Password: [Generated securely]"
}
download_dezerx() {
if [[ "$OPERATION_MODE" == "install" ]]; then
print_step "8" "DOWNLOADING DEZERX"
else
print_step "6" "DOWNLOADING DEZERX UPDATE"
fi
print_info "Requesting download URL from DezerX servers..."
local temp_file=$(mktemp)
local http_code
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/download)
if [[ "$http_code" != "200" ]]; then
print_error "Failed to get download URL (HTTP: $http_code)"
if [[ -f "$temp_file" ]]; then
local error_msg=$(cat "$temp_file" 2>/dev/null || echo "Unknown error")
print_error "Server response: $error_msg"
fi
rm -f "$temp_file"
if [[ "$OPERATION_MODE" == "update" ]]; then
restore_backup
fi
exit 1
fi
local download_url
if command -v jq &>/dev/null; then
download_url=$(jq -r '.download_url' "$temp_file" 2>/dev/null)
else
download_url=$(grep -o '"download_url":"[^"]*' "$temp_file" | cut -d'"' -f4 | sed 's/\\//g')
fi
rm -f "$temp_file"
if [[ -z "$download_url" || "$download_url" == "null" ]]; then
print_error "Failed to extract download URL from server response"
if [[ "$OPERATION_MODE" == "update" ]]; then
restore_backup
fi
exit 1
fi
if [[ "$OPERATION_MODE" == "install" ]]; then
print_info "Creating installation directory: $INSTALL_DIR"
mkdir -p "$INSTALL_DIR"
fi
print_info "Downloading DezerX package..."
local download_file="/tmp/dezerx-$(date +%s).zip"
if ! curl -L -o "$download_file" \
--progress-bar \
--connect-timeout 30 \
--max-time 300 \
"$download_url"; then
print_error "Download failed"