-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathsetup.sh
More file actions
1455 lines (1245 loc) · 67.1 KB
/
setup.sh
File metadata and controls
1455 lines (1245 loc) · 67.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
# --- Configuration Variables ---
PROJECT_NAME="CandyPanel"
REPO_URL="https://github.com/AmiRCandy/Candy-Panel.git"
PROJECT_ROOT="/var/www/$PROJECT_NAME"
BACKEND_DIR="$PROJECT_ROOT/Backend"
FRONTEND_DIR="$PROJECT_ROOT/Frontend"
FLASK_APP_ENTRY="main.py" # Ensure this is the file where your Flask app is defined and serves static files
LINUX_USER=$(whoami)
# --- Backend specific configuration ---
# Flask will now serve both frontend and backend on this port
BACKEND_HOST="0.0.0.0"
BACKEND_PORT="3446" # This will be the publicly accessible port for everything
# NVM specific
NVM_VERSION="v0.40.3" # Always check https://github.com/nvm-sh/nvm for the latest version
NODE_VERSION="22" # Install Node.js v22.x.x
SUDOERS_FILE="/etc/sudoers.d/candypanel_permissions" # For uninstall script
# --- Styling Functions ---
GREEN='\e[32m'
BLUE='\e[34m'
RED='\e[31m'
YELLOW='\e[33m'
CYAN='\e[36m'
RESET='\e[0m'
BOLD='\e[1m'
UNDERLINE='\e[4m'
print_header() {
local title=$1
echo -e "\n${BOLD}${CYAN}====================================================${RESET}"
echo -e "${BOLD}${CYAN} $title ${RESET}"
echo -e "${BOLD}${CYAN}====================================================${RESET}"
echo -e "${BOLD}${YELLOW} Project: $PROJECT_NAME${RESET}"
echo -e "${BOLD}${YELLOW} Repo: $REPO_URL${RESET}"
echo -e "${BOLD}${YELLOW} User: $LINUX_USER${RESET}"
echo -e "${BOLD}${CYAN}====================================================${RESET}\n"
sleep 1
}
print_info() {
echo -e "${BLUE}INFO:${RESET} $1"
}
print_success() {
echo -e "${GREEN}SUCCESS:${RESET} $1"
}
print_error() {
echo -e "${RED}ERROR:${RESET} $1" >&2
}
print_warning() {
echo -e "${YELLOW}WARNING:${RESET} $1"
}
confirm_action() {
read -p "$(echo -e "${YELLOW}CONFIRM:${RESET} $1 (y/N)? ") " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
print_error "Operation cancelled by user."
exit 1
fi
}
# --- Install Functions ---
check_prerequisites() {
print_info "Checking for required system packages..."
local missing_packages=()
# Get the system's default Python 3 version
PYTHON_VERSION=$(python3 -c "import sys; print(f'python3.{sys.version_info.minor}')")
PYTHON_VENV_PACKAGE="${PYTHON_VERSION}-venv"
for cmd in git python3 ufw cron build-essential python3-dev openresolv; do
if ! command -v "$cmd" &> /dev/null; then
missing_packages+=("$cmd")
fi
done
# Add the specific python3-venv package based on the system's Python 3 version
if ! dpkg -s "$PYTHON_VENV_PACKAGE" &> /dev/null; then
missing_packages+=("$PYTHON_VENV_PACKAGE")
fi
if ! command -v curl &> /dev/null; then
missing_packages+=("curl")
fi
if [ ${#missing_packages[@]} -gt 0 ]; then
print_warning "The following required packages are not installed: ${missing_packages[*]}"
confirm_action "Attempt to install missing packages?"
local package_manager=""
if command -v apt &> /dev/null; then
package_manager="apt"
elif command -v yum &> /dev/null; then
package_manager="yum"
else
print_error "No supported package manager (apt or yum) found. Please install packages manually."
exit 1
fi
print_info "Using $package_manager to install missing packages..."
if [ "$package_manager" == "apt" ]; then
sudo apt update && sudo apt install -y "${missing_packages[@]}"
elif [ "$package_manager" == "yum" ]; then
sudo yum install -y "${missing_packages[@]}"
fi
if [ $? -ne 0 ]; then
print_error "Failed to install some required packages. Please check the output and install them manually."
#exit 1
else
print_success "Missing packages installed successfully."
fi
else
print_success "All required system packages found."
fi
sleep 1
}
setup_permissions() {
print_info "--- Setting up System Permissions and Installing Core Dependencies ---"
sleep 1
read -p "$(echo -e "${YELLOW}INPUT:${RESET} Please enter the username that will run the CandyPanel application (e.g., candypaneluser): ")" CANDYPANEL_USER
if ! id "$CANDYPANEL_USER" &>/dev/null; then
print_error "Error: User '$CANDYPANEL_USER' does not exist."
print_error "Please create the user first (e.g., 'sudo adduser $CANDYPANEL_USER') or enter an existing one."
exit 1
fi
echo "User '$CANDYPANEL_USER' selected for CandyPanel operations."
print_info "Installing core system packages: wireguard, qrencode, python3-psutil..."
sudo apt install -y wireguard qrencode python3-psutil || { print_error "Failed to install core system packages."; exit 1; }
print_success "Core system packages installed."
print_info "Configuring sudoers for user '$CANDYPANEL_USER' to allow specific commands without password..."
cat <<EOF | sudo tee "$SUDOERS_FILE" > /dev/null
# Allow $CANDYPANEL_USER to manage WireGuard, UFW, systemctl, and cron for CandyPanel
$CANDYPANEL_USER ALL=(ALL) NOPASSWD: /usr/bin/wg genkey, /usr/bin/wg pubkey, /usr/bin/wg show *, /usr/bin/wg syncconf *, /usr/bin/wg-quick up *, /usr/bin/wg-quick down *, /usr/bin/systemctl enable wg-quick@*, /usr/bin/systemctl start wg-quick@*, /usr/bin/systemctl stop wg-quick@*, /usr/sbin/ufw allow *, /usr/sbin/ufw delete *, /usr/bin/crontab
EOF
sudo chmod 0440 "$SUDOERS_FILE" || { print_error "Failed to set permissions for sudoers file."; exit 1; }
print_success "Sudoers configured successfully in '$SUDOERS_FILE'."
print_info "You can verify the sudoers file with: 'sudo visudo -cf $SUDOERS_FILE'"
sleep 1
}
install_nodejs_with_nvm() {
print_info "--- Installing Node.js and npm using NVM ---"
sleep 1
if [ -s "$HOME/.nvm/nvm.sh" ]; then
print_warning "NVM appears to be already installed. Sourcing it..."
. "$HOME/.nvm/nvm.sh"
else
print_info "Installing NVM (Node Version Manager)..."
curl -o- "https://raw.githubusercontent.com/nvm-sh/nvm/$NVM_VERSION/install.sh" | bash || { print_error "Failed to download and install NVM."; exit 1; }
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"
if ! command -v nvm &> /dev/null; then
print_error "NVM command not found after installation and sourcing. Please check NVM installation manually."
exit 1
fi
print_success "NVM installed successfully."
fi
print_info "Installing Node.js v${NODE_VERSION} (and bundled npm)..."
nvm install "$NODE_VERSION" || { print_error "Failed to install Node.js v${NODE_VERSION}."; exit 1; }
print_success "Node.js v${NODE_VERSION} and npm installed."
print_info "Setting Node.js v${NODE_VERSION} as the default version..."
nvm alias default "$NODE_VERSION" || { print_error "Failed to set default Node.js version."; exit 1; }
print_success "Node.js v${NODE_VERSION} set as default."
print_info "Using Node.js v${NODE_VERSION} for current session..."
nvm use "$NODE_VERSION" || { print_error "Failed to switch to Node.js v${NODE_VERSION}."; exit 1; }
print_success "Node.js v${NODE_VERSION} is now active."
node -v
npm -v
sleep 1
}
clone_or_update_repo() {
print_info "Starting deployment process for $PROJECT_NAME..."
sleep 1
if [ -d "$PROJECT_ROOT" ]; then
print_warning "Project directory '$PROJECT_ROOT' already exists."
confirm_action "Do you want to pull the latest changes from the repository?"
print_info "Navigating to $PROJECT_ROOT and pulling latest changes..."
sudo git -C "$PROJECT_ROOT" pull origin main || sudo git -C "$PROJECT_ROOT" pull origin main
if [ $? -ne 0 ]; then
print_error "Failed to pull latest changes from repository. Check permissions or network."
exit 1
fi
print_success "Repository updated."
else
print_info "Cloning repository '$REPO_URL' into '$PROJECT_ROOT'..."
sudo mkdir -p "$(dirname "$PROJECT_ROOT")"
sudo git clone --branch main --single-branch "$REPO_URL" "$PROJECT_ROOT" || { print_error "Failed to clone repository"; exit 1; }
sudo chown -R "$LINUX_USER:$LINUX_USER" "$PROJECT_ROOT" || { print_warning "Could not change ownership of $PROJECT_ROOT to $LINUX_USER. Manual intervention might be needed for permissions."; }
print_success "Repository cloned successfully."
fi
sleep 1
}
deploy_backend() {
print_info "--- Deploying Flask Backend ---"
sleep 1
print_info "Navigating to backend directory: $BACKEND_DIR"
cd "$BACKEND_DIR" || { print_error "Backend directory not found: $BACKEND_DIR"; exit 1; }
print_info "Creating and activating Python virtual environment..."
# Use the discovered Python executable
python3 -m venv venv || { print_error "Failed to create virtual environment."; exit 1; }
source venv/bin/activate || { print_error "Failed to activate virtual environment."; exit 1; }
print_success "Virtual environment activated."
sleep 1
print_info "Installing Python dependencies (Flask etc.)..."
# Install netifaces with required build dependencies if needed
pip install pyrogram flask[async] requests flask_cors psutil httpx tgcrypto nanoid || { print_error "Failed to install Python dependencies."; exit 1; }
print_info "Attempting to install netifaces specifically, including build dependencies..."
# Try installing netifaces with potential build dependencies for different distros
if command -v apt &> /dev/null; then
sudo apt install -y python3-netifaces || { print_error "Failed to install netifaces. Check build-essential and python3-dev installations."; exit 1; }
pip install netifaces || { print_error "Failed to install netifaces. Check build-essential and python3-dev installations."; exit 1; }
elif command -v yum &> /dev/null; then
sudo yum install -y python3-netifaces || { print_error "Failed to install netifaces. Check build-essential and python3-devel installations."; exit 1; }
pip install netifaces || { print_error "Failed to install netifaces. Check build-essential and python3-dev installations."; exit 1; }
else
pip install netifaces || print_warning "Failed to install netifaces. Please install it manually with appropriate system headers if needed."
fi
print_success "Python dependencies installed."
sleep 1
print_info "Creating Systemd service file for Flask..."
sudo tee "/etc/systemd/system/${PROJECT_NAME}_flask.service" > /dev/null <<EOF
[Unit]
Description=Flask instance for ${PROJECT_NAME}
After=network.target
[Service]
User=$LINUX_USER
Group=$LINUX_USER
WorkingDirectory=$BACKEND_DIR
Environment="FLASK_APP=$FLASK_APP_ENTRY"
Environment="FLASK_RUN_HOST=$BACKEND_HOST"
Environment="FLASK_RUN_PORT=$BACKEND_PORT"
ExecStart=$BACKEND_DIR/venv/bin/python3 $FLASK_APP_ENTRY
Restart=always
RestartSec=5s
[Install]
WantedBy=multi-user.target
EOF
print_success "Systemd service file created."
sleep 1
print_info "Reloading Systemd daemon, enabling and starting Flask service..."
sudo systemctl daemon-reload || { print_error "Failed to reload Systemd daemon."; exit 1; }
sudo systemctl enable "${PROJECT_NAME}_flask.service" || { print_error "Failed to enable Flask service."; exit 1; }
sudo systemctl enable cron
sudo systemctl start "${PROJECT_NAME}_flask.service" || { print_error "Failed to start Flask service."; exit 1; }
sudo systemctl start cron
print_success "Flask service started and enabled to run on boot."
print_info "You can check its status with: sudo systemctl status ${PROJECT_NAME}_flask.service"
print_info "View logs with: journalctl -u ${PROJECT_NAME}_flask.service --since '1 hour ago'"
sleep 2
}
deploy_frontend() {
print_info "--- Deploying React Vite Frontend ---"
sleep 1
print_info "Navigating to frontend directory: $FRONTEND_DIR"
cd "$FRONTEND_DIR" || { print_error "Frontend directory not found: $FRONTEND_DIR"; exit 1; }
if [ -s "$HOME/.nvm/nvm.sh" ]; then
. "$HOME/.nvm/nvm.sh"
nvm use "$NODE_VERSION" || print_warning "Could not activate Node.js v${NODE_VERSION} with nvm in this subshell. Continuing anyway."
else
print_error "NVM not found or not sourced. Node.js/npm commands might fail."
exit 1
fi
print_info "Installing Node.js dependencies..."
npm install || { print_error "Failed to install Node.js dependencies. Check npm logs and internet connection."; exit 1; }
print_success "Node.js dependencies installed."
sleep 1
}
configure_frontend_api_url() {
print_info "--- Configuring Frontend API URL ---"
sleep 1
local server_ip
read -p "$(echo -e "${YELLOW}INPUT:${RESET} Enter your server's public IP address (e.g., 192.168.1.100) or domain name if using one: ")" server_ip
if [ -z "$server_ip" ]; then
print_error "Server IP/Domain cannot be empty. Exiting."
exit 1
fi
local frontend_api_url="http://$server_ip:$BACKEND_PORT"
print_info "Writing frontend environment variable VITE_APP_API_URL to .env.production..."
echo "export VITE_APP_API_URL=$frontend_api_url" | sudo tee "$FRONTEND_DIR/.env.production" > /dev/null || { print_error "Failed to write .env.production file. Check permissions."; exit 1; }
echo "export AP_PORT=$BACKEND_PORT" | sudo tee "$FRONTEND_DIR/.env.production" > /dev/null || { print_error "Failed to write .env.production file. Check permissions."; exit 1; }
print_success ".env.production created/updated with VITE_APP_API_URL=$frontend_api_url"
sudo chown "$LINUX_USER:$LINUX_USER" "$FRONTEND_DIR/.env.production" || { print_warning "Could not change ownership of .env.production. Manual intervention might be needed for permissions."; }
sleep 1
print_info "Rebuilding frontend to apply new API URL..."
cd "$FRONTEND_DIR" || { print_error "Frontend directory not found: $FRONTEND_DIR"; exit 1; }
npm run build || { print_error "Failed to rebuild React Vite frontend after updating API URL."; exit 1; }
print_success "Frontend rebuilt successfully with updated API URL."
sleep 1
}
configure_firewall() {
print_info "--- Configuring Firewall (UFW) ---"
sleep 1
print_info "Enabling UFW (if not already enabled)..."
sudo ufw status | grep -q "Status: active" || sudo ufw enable
print_success "UFW is active."
sleep 1
local ssh_port
if [ -n "$SSH_CLIENT" ]; then
ssh_port=$(echo "$SSH_CLIENT" | awk '{print $3}')
print_info "Detected SSH port: $ssh_port"
print_info "Allowing SSH access on port $ssh_port..."
sudo ufw allow "$ssh_port"/tcp || { print_error "Failed to allow SSH port $ssh_port through UFW."; exit 1; }
print_success "SSH port $ssh_port allowed for external access."
else
print_warning "Could not detect SSH port from \$SSH_CLIENT. Please ensure SSH access is configured manually if needed."
fi
print_info "Allowing external access to port $BACKEND_PORT for Flask application..."
sudo ufw allow "$BACKEND_PORT"/tcp || { print_error "Failed to allow port $BACKEND_PORT through UFW."; exit 1; }
print_success "Port $BACKEND_PORT allowed for external access."
print_info "You can check UFW status with: sudo ufw status"
sleep 2
}
# --- Uninstall Functions ---
get_backend_port() {
if [ -n "$AP_PORT" ]; then
BACKEND_PORT="$AP_PORT"
print_info "Using BACKEND_PORT from AP_PORT environment variable: $BACKEND_PORT"
else
while true; do
read -p "$(echo -e "${YELLOW}INPUT:${RESET} Please enter the backend port used by CandyPanel (e.g., 3446): ")" user_port
if [[ "$user_port" =~ ^[0-9]+$ ]] && [ "$user_port" -ge 1 ] && [ "$user_port" -le 65535 ]; then
BACKEND_PORT="$user_port"
print_info "Using BACKEND_PORT from user input: $BACKEND_PORT"
break
else
print_error "Invalid port number. Please enter a number between 1 and 65535."
fi
done
fi
export BACKEND_PORT
sleep 1
}
uninstall_backend_service() {
print_info "--- Stopping and Disabling Flask Backend Service ---"
sleep 1
local service_name="${PROJECT_NAME}_flask.service"
if sudo systemctl is-active --quiet "$service_name"; then
print_info "Stopping Flask service: $service_name..."
sudo systemctl stop "$service_name" || { print_warning "Failed to stop Flask service. It might not be running."; }
print_success "Flask service stopped."
else
print_info "Flask service '$service_name' is not active."
fi
if sudo systemctl is-enabled --quiet "$service_name"; then
print_info "Disabling Flask service: $service_name..."
sudo systemctl disable "$service_name" || { print_warning "Failed to disable Flask service. It might already be disabled."; }
print_success "Flask service disabled."
else
print_info "Flask service '$service_name' is not enabled."
fi
if [ -f "/etc/systemd/system/$service_name" ]; then
print_info "Removing Systemd service file: /etc/systemd/system/$service_name..."
sudo rm "/etc/systemd/system/$service_name" || { print_error "Failed to remove Systemd service file."; exit 1; }
print_success "Systemd service file removed."
else
print_info "Systemd service file '/etc/systemd/system/$service_name' not found."
fi
print_info "Reloading Systemd daemon..."
sudo systemctl daemon-reload || { print_warning "Failed to reload Systemd daemon. This might not be critical for uninstallation."; }
print_success "Systemd daemon reloaded."
sleep 2
}
remove_project_directory() {
print_info "--- Removing Project Directory ---"
sleep 1
if [ -d "$PROJECT_ROOT" ]; then
confirm_action "Are you sure you want to delete the project directory '$PROJECT_ROOT' and all its contents? This action is irreversible."
print_info "Deleting project directory: $PROJECT_ROOT..."
sudo rm -rf "$PROJECT_ROOT" || { print_error "Failed to remove project directory. Check permissions."; exit 1; }
print_success "Project directory '$PROJECT_ROOT' removed successfully."
else
print_info "Project directory '$PROJECT_ROOT' does not exist. Nothing to remove."
fi
sleep 1
}
remove_firewall_rules() {
print_info "--- Removing Firewall Rules ---"
sleep 1
if sudo ufw status | grep -q "Status: active"; then
print_info "Checking for UFW rule for port $BACKEND_PORT..."
if sudo ufw status | grep -q "ALLOW IN.*$BACKEND_PORT/tcp"; then
print_info "Deleting UFW rule for port $BACKEND_PORT..."
sudo ufw delete allow $BACKEND_PORT/tcp || { print_warning "Failed to delete UFW rule for port $BACKEND_PORT. Manual removal might be needed."; }
print_success "UFW rule for port $BACKEND_PORT removed."
else
print_info "No UFW rule found for port $BACKEND_PORT."
fi
else
print_info "UFW is not active. No firewall rules to remove via UFW."
fi
sleep 1
}
uninstall_nvm() {
print_info "--- Uninstalling NVM and Node.js (Optional) ---"
sleep 1
if [ -d "$HOME/.nvm" ]; then
confirm_action "Do you want to uninstall NVM (Node Version Manager) and all Node.js versions managed by it? This will remove '$HOME/.nvm'."
print_info "Attempting to uninstall NVM..."
if [ -s "$HOME/.nvm/nvm.sh" ]; then
. "$HOME/.nvm/nvm.sh"
nvm deactivate > /dev/null 2>&1
nvm uninstall --lts > /dev/null 2>&1
nvm uninstall "$(nvm current)" > /dev/null 2>&1
fi
rm -rf "$HOME/.nvm"
sed -i '/NVM_DIR/d' "$HOME/.bashrc" "$HOME/.zshrc" "$HOME/.profile" 2>/dev/null
sed -i '/nvm.sh/d' "$HOME/.bashrc" "$HOME/.zshrc" "$HOME/.profile" 2>/dev/null
sed -i '/bash_completion/d' "$HOME/.bashrc" "$HOME/.zshrc" "$HOME/.profile" 2>/dev/null
print_success "NVM and associated Node.js versions removed."
print_warning "You may need to manually remove any remaining Node.js related binaries from your PATH if they were installed globally outside NVM."
else
print_info "NVM directory '$HOME/.nvm' not found. Nothing to uninstall."
fi
sleep 1
}
remove_sudoers_file() {
print_info "--- Removing Sudoers Configuration ---"
sleep 1
if [ -f "$SUDOERS_FILE" ]; then
confirm_action "Do you want to remove the sudoers file '$SUDOERS_FILE' created for CandyPanel permissions? This will revoke specific passwordless sudo access for the CandyPanel user."
print_info "Removing sudoers file: $SUDOERS_FILE..."
sudo rm "$SUDOERS_FILE" || { print_error "Failed to remove sudoers file. Manual removal might be needed."; exit 1; }
print_success "Sudoers file removed."
else
print_info "Sudoers file '$SUDOERS_FILE' not found. Nothing to remove."
fi
sleep 1
}
uninstall_wireguard() {
print_info "--- Uninstalling WireGuard and its Configurations ---"
sleep 1
confirm_action "Do you want to uninstall WireGuard and remove its configuration files? This will remove all VPN configurations."
print_info "Attempting to stop all active WireGuard interfaces..."
for conf_file in /etc/wireguard/*.conf; do
if [ -f "$conf_file" ]; then
local interface_name=$(basename "$conf_file" .conf)
print_info "Stopping WireGuard interface: $interface_name..."
sudo wg-quick down "$interface_name" > /dev/null 2>&1 || print_warning "Could not stop WireGuard interface '$interface_name'. It might not be active or already stopped."
sudo systemctl disable "wg-quick@${interface_name}.service" > /dev/null 2>&1 || print_warning "Could not disable WireGuard service for '$interface_name'. It might not be enabled."
sudo rm -f "/etc/systemd/system/wg-quick@${interface_name}.service" > /dev/null 2>&1
fi
done
print_success "Attempted to stop and disable WireGuard interfaces."
print_info "Removing WireGuard packages (wireguard and wireguard-tools)..."
if command -v apt &> /dev/null; then
sudo apt purge -y wireguard wireguard-tools || print_warning "Failed to purge WireGuard packages. They might not be installed or require manual removal."
elif command -v dnf &> /dev/null; then
sudo dnf remove -y wireguard-tools || print_warning "Failed to remove WireGuard packages. They might not be installed or require manual removal."
elif command -v pacman &> /dev/null; then
sudo pacman -Rs --noconfirm wireguard-tools || print_warning "Failed to remove WireGuard packages. They might not be installed or require manual removal."
else
print_warning "Package manager not recognized. Please manually uninstall 'wireguard' and 'wireguard-tools' packages."
fi
print_success "WireGuard packages removal attempt complete."
print_info "Removing WireGuard configuration directory: /etc/wireguard/..."
if [ -d "/etc/wireguard/" ]; then
sudo rm -rf "/etc/wireguard/" || { print_error "Failed to remove /etc/wireguard/. Check permissions."; }
print_success "WireGuard configuration directory removed."
else
print_info "/etc/wireguard/ directory not found. Nothing to remove."
fi
print_info "Removing WireGuard connections from NetworkManager (if any)..."
if command -v nmcli &> /dev/null; then
local wg_connections=$(nmcli -t -f UUID,TYPE connection show --active | grep 'wireguard' | cut -d':' -f1)
if [ -n "$wg_connections" ]; then
for uuid in $wg_connections; do
print_info "Deleting NetworkManager WireGuard connection (UUID: $uuid)..."
sudo nmcli connection delete uuid "$uuid" || print_warning "Failed to delete NetworkManager WireGuard connection $uuid."
done
print_success "NetworkManager WireGuard connections removed."
else
print_info "No active WireGuard connections found in NetworkManager."
fi
else
print_info "nmcli (NetworkManager CLI) not found. Skipping NetworkManager cleanup."
fi
print_info "Reloading Systemd daemon after WireGuard cleanup..."
sudo systemctl daemon-reload || { print_warning "Failed to reload Systemd daemon. This might not be critical."; }
print_success "Systemd daemon reloaded."
sleep 2
}
# --- Main Install/Update/Uninstall Logic ---
run_install() {
print_header "Candy Panel Deployment Script"
confirm_action "This script will deploy your Candy panel with Flask serving both frontend and backend. Ensure you have updated the REPO_URL variable in the script."
check_prerequisites
setup_permissions
install_nodejs_with_nvm
clone_or_update_repo
# Prompt for IPv6 information
local ipv6_address_range
local ipv6_dns
read -p "$(echo -e "${YELLOW}INPUT:${RESET} Do you want to enable IPv6 support? (y/N)? ")" -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
read -p "$(echo -e "${YELLOW}INPUT:${RESET} Enter IPv6 Address Range for WireGuard clients (e.g., fd86:ea04:1115::1/64): ")" ipv6_address_range
read -p "$(echo -e "${YELLOW}INPUT:${RESET} Enter IPv6 DNS Server (e.g., 2001:4860:4860::8888): ")" ipv6_dns
fi
deploy_backend "$ipv6_address_range" "$ipv6_dns"
deploy_frontend
configure_frontend_api_url
configure_firewall
echo -e "\n${BOLD}${GREEN}====================================================${RESET}"
echo-e "${BOLD}${GREEN} Deployment Complete! ${RESET}"
echo -e "${BOLD}${GREEN}====================================================${RESET}"
echo -e "${BOLD}${GREEN} Your Candy Panel should now be accessible at:${RESET}"
echo -e "${BOLD}${GREEN} http://YOUR_SERVER_IP:$BACKEND_PORT${RESET}"
print_warning "Remember to replace YOUR_SERVER_IP with your actual server's public IP address."
print_warning "Note: SSL is NOT configured with this setup. For HTTPS, you will need to add a reverse proxy like Nginx or Caddy."
echo -e "${BOLD}${GREEN}====================================================${RESET}\n"
print_info "Ensure the Linux user '$LINUX_USER' has appropriate permissions for WireGuard operations."
print_info "Flask application is running on port $BACKEND_PORT and serving all content."
}
# A separate function for backend deployment to pass the new variables
deploy_backend() {
local ipv6_address_range=$1
local ipv6_dns=$2
print_info "--- Deploying Flask Backend ---"
sleep 1
print_info "Navigating to backend directory: $BACKEND_DIR"
cd "$BACKEND_DIR" || { print_error "Backend directory not found: $BACKEND_DIR"; exit 1; }
print_info "Creating and activating Python virtual environment..."
# Use the discovered Python executable
python3 -m venv venv || { print_error "Failed to create virtual environment."; exit 1; }
source venv/bin/activate || { print_error "Failed to activate virtual environment."; exit 1; }
print_success "Virtual environment activated."
sleep 1
print_info "Installing Python dependencies (Flask etc.)..."
# Install netifaces with required build dependencies if needed
pip install pyrogram flask[async] requests flask_cors psutil httpx tgcrypto nanoid || { print_error "Failed to install Python dependencies."; exit 1; }
print_info "Attempting to install netifaces specifically, including build dependencies..."
# Try installing netifaces with potential build dependencies for different distros
if command -v apt &> /dev/null; then
sudo apt install -y python3-netifaces || { print_error "Failed to install netifaces. Check build-essential and python3-dev installations."; exit 1; }
pip install netifaces || { print_error "Failed to install netifaces. Check build-essential and python3-dev installations."; exit 1; }
elif command -v yum &> /dev/null; then
sudo yum install -y python3-netifaces || { print_error "Failed to install netifaces. Check build-essential and python3-devel installations."; exit 1; }
pip install netifaces || { print_error "Failed to install netifaces. Check build-essential and python3-dev installations."; exit 1; }
else
pip install netifaces || print_warning "Failed to install netifaces. Please install it manually with appropriate system headers if needed."
fi
print_success "Python dependencies installed."
sleep 1
print_info "Creating Systemd service file for Flask..."
sudo tee "/etc/systemd/system/${PROJECT_NAME}_flask.service" > /dev/null <<EOF
[Unit]
Description=Flask instance for ${PROJECT_NAME}
After=network.target
[Service]
User=$LINUX_USER
Group=$LINUX_USER
WorkingDirectory=$BACKEND_DIR
Environment="FLASK_APP=$FLASK_APP_ENTRY"
Environment="FLASK_RUN_HOST=$BACKEND_HOST"
Environment="FLASK_RUN_PORT=$BACKEND_PORT"
Environment="WG_IPV6_ADDRESS=$ipv6_address_range"
Environment="WG_IPV6_DNS=$ipv6_dns"
ExecStart=$BACKEND_DIR/venv/bin/python3 $FLASK_APP_ENTRY
Restart=always
RestartSec=5s
[Install]
WantedBy=multi-user.target
EOF
print_success "Systemd service file created."
sleep 1
print_info "Reloading Systemd daemon, enabling and starting Flask service..."
sudo systemctl daemon-reload || { print_error "Failed to reload Systemd daemon."; exit 1; }
sudo systemctl enable "${PROJECT_NAME}_flask.service" || { print_error "Failed to enable Flask service."; exit 1; }
sudo systemctl enable cron
sudo systemctl start "${PROJECT_NAME}_flask.service" || { print_error "Failed to start Flask service."; exit 1; }
sudo systemctl start cron
print_success "Flask service started and enabled to run on boot."
print_info "You can check its status with: sudo systemctl status ${PROJECT_NAME}_flask.service"
print_info "View logs with: journalctl -u ${PROJECT_NAME}_flask.service --since '1 hour ago'"
sleep 2
}
deploy_frontend() {
print_info "--- Deploying React Vite Frontend ---"
sleep 1
print_info "Navigating to frontend directory: $FRONTEND_DIR"
cd "$FRONTEND_DIR" || { print_error "Frontend directory not found: $FRONTEND_DIR"; exit 1; }
if [ -s "$HOME/.nvm/nvm.sh" ]; then
. "$HOME/.nvm/nvm.sh"
nvm use "$NODE_VERSION" || print_warning "Could not activate Node.js v${NODE_VERSION} with nvm in this subshell. Continuing anyway."
else
print_error "NVM not found or not sourced. Node.js/npm commands might fail."
exit 1
fi
print_info "Installing Node.js dependencies..."
npm install || { print_error "Failed to install Node.js dependencies. Check npm logs and internet connection."; exit 1; }
print_success "Node.js dependencies installed."
sleep 1
}
configure_frontend_api_url() {
print_info "--- Configuring Frontend API URL ---"
sleep 1
local server_ip
read -p "$(echo -e "${YELLOW}INPUT:${RESET} Enter your server's public IP address (e.g., 192.168.1.100) or domain name if using one: ")" server_ip
if [ -z "$server_ip" ]; then
print_error "Server IP/Domain cannot be empty. Exiting."
exit 1
fi
local frontend_api_url="http://$server_ip:$BACKEND_PORT"
print_info "Writing frontend environment variable VITE_APP_API_URL to .env.production..."
echo "export VITE_APP_API_URL=$frontend_api_url" | sudo tee "$FRONTEND_DIR/.env.production" > /dev/null || { print_error "Failed to write .env.production file. Check permissions."; exit 1; }
echo "export AP_PORT=$BACKEND_PORT" | sudo tee "$FRONTEND_DIR/.env.production" > /dev/null || { print_error "Failed to write .env.production file. Check permissions."; exit 1; }
print_success ".env.production created/updated with VITE_APP_API_URL=$frontend_api_url"
sudo chown "$LINUX_USER:$LINUX_USER" "$FRONTEND_DIR/.env.production" || { print_warning "Could not change ownership of .env.production. Manual intervention might be needed for permissions."; }
sleep 1
print_info "Rebuilding frontend to apply new API URL..."
cd "$FRONTEND_DIR" || { print_error "Frontend directory not found: $FRONTEND_DIR"; exit 1; }
npm run build || { print_error "Failed to rebuild React Vite frontend after updating API URL."; exit 1; }
print_success "Frontend rebuilt successfully with updated API URL."
sleep 1
}
configure_firewall() {
print_info "--- Configuring Firewall (UFW) ---"
sleep 1
print_info "Enabling UFW (if not already enabled)..."
sudo ufw status | grep -q "Status: active" || sudo ufw enable
print_success "UFW is active."
sleep 1
local ssh_port
if [ -n "$SSH_CLIENT" ]; then
ssh_port=$(echo "$SSH_CLIENT" | awk '{print $3}')
print_info "Detected SSH port: $ssh_port"
print_info "Allowing SSH access on port $ssh_port..."
sudo ufw allow "$ssh_port"/tcp || { print_error "Failed to allow SSH port $ssh_port through UFW."; exit 1; }
print_success "SSH port $ssh_port allowed for external access."
else
print_warning "Could not detect SSH port from \$SSH_CLIENT. Please ensure SSH access is configured manually if needed."
fi
print_info "Allowing external access to port $BACKEND_PORT for Flask application..."
sudo ufw allow "$BACKEND_PORT"/tcp || { print_error "Failed to allow port $BACKEND_PORT through UFW."; exit 1; }
print_success "Port $BACKEND_PORT allowed for external access."
print_info "You can check UFW status with: sudo ufw status"
sleep 2
}
# --- Uninstall Functions ---
get_backend_port() {
if [ -n "$AP_PORT" ]; then
BACKEND_PORT="$AP_PORT"
print_info "Using BACKEND_PORT from AP_PORT environment variable: $BACKEND_PORT"
else
while true; do
read -p "$(echo -e "${YELLOW}INPUT:${RESET} Please enter the backend port used by CandyPanel (e.g., 3446): ")" user_port
if [[ "$user_port" =~ ^[0-9]+$ ]] && [ "$user_port" -ge 1 ] && [ "$user_port" -le 65535 ]; then
BACKEND_PORT="$user_port"
print_info "Using BACKEND_PORT from user input: $BACKEND_PORT"
break
else
print_error "Invalid port number. Please enter a number between 1 and 65535."
fi
done
fi
export BACKEND_PORT
sleep 1
}
uninstall_backend_service() {
print_info "--- Stopping and Disabling Flask Backend Service ---"
sleep 1
local service_name="${PROJECT_NAME}_flask.service"
if sudo systemctl is-active --quiet "$service_name"; then
print_info "Stopping Flask service: $service_name..."
sudo systemctl stop "$service_name" || { print_warning "Failed to stop Flask service. It might not be running."; }
print_success "Flask service stopped."
else
print_info "Flask service '$service_name' is not active."
fi
if sudo systemctl is-enabled --quiet "$service_name"; then
print_info "Disabling Flask service: $service_name..."
sudo systemctl disable "$service_name" || { print_warning "Failed to disable Flask service. It might already be disabled."; }
print_success "Flask service disabled."
else
print_info "Flask service '$service_name' is not enabled."
fi
if [ -f "/etc/systemd/system/$service_name" ]; then
print_info "Removing Systemd service file: /etc/systemd/system/$service_name..."
sudo rm "/etc/systemd/system/$service_name" || { print_error "Failed to remove Systemd service file."; exit 1; }
print_success "Systemd service file removed."
else
print_info "Systemd service file '/etc/systemd/system/$service_name' not found."
fi
print_info "Reloading Systemd daemon..."
sudo systemctl daemon-reload || { print_warning "Failed to reload Systemd daemon. This might not be critical for uninstallation."; }
print_success "Systemd daemon reloaded."
sleep 2
}
remove_project_directory() {
print_info "--- Removing Project Directory ---"
sleep 1
if [ -d "$PROJECT_ROOT" ]; then
confirm_action "Are you sure you want to delete the project directory '$PROJECT_ROOT' and all its contents? This action is irreversible."
print_info "Deleting project directory: $PROJECT_ROOT..."
sudo rm -rf "$PROJECT_ROOT" || { print_error "Failed to remove project directory. Check permissions."; exit 1; }
print_success "Project directory '$PROJECT_ROOT' removed successfully."
else
print_info "Project directory '$PROJECT_ROOT' does not exist. Nothing to remove."
fi
sleep 1
}
remove_firewall_rules() {
print_info "--- Removing Firewall Rules ---"
sleep 1
if sudo ufw status | grep -q "Status: active"; then
print_info "Checking for UFW rule for port $BACKEND_PORT..."
if sudo ufw status | grep -q "ALLOW IN.*$BACKEND_PORT/tcp"; then
print_info "Deleting UFW rule for port $BACKEND_PORT..."
sudo ufw delete allow $BACKEND_PORT/tcp || { print_warning "Failed to delete UFW rule for port $BACKEND_PORT. Manual removal might be needed."; }
print_success "UFW rule for port $BACKEND_PORT removed."
else
print_info "No UFW rule found for port $BACKEND_PORT."
fi
else
print_info "UFW is not active. No firewall rules to remove via UFW."
fi
sleep 1
}
uninstall_nvm() {
print_info "--- Uninstalling NVM and Node.js (Optional) ---"
sleep 1
if [ -d "$HOME/.nvm" ]; then
confirm_action "Do you want to uninstall NVM (Node Version Manager) and all Node.js versions managed by it? This will remove '$HOME/.nvm'."
print_info "Attempting to uninstall NVM..."
if [ -s "$HOME/.nvm/nvm.sh" ]; then
. "$HOME/.nvm/nvm.sh"
nvm deactivate > /dev/null 2>&1
nvm uninstall --lts > /dev/null 2>&1
nvm uninstall "$(nvm current)" > /dev/null 2>&1
fi
rm -rf "$HOME/.nvm"
sed -i '/NVM_DIR/d' "$HOME/.bashrc" "$HOME/.zshrc" "$HOME/.profile" 2>/dev/null
sed -i '/nvm.sh/d' "$HOME/.bashrc" "$HOME/.zshrc" "$HOME/.profile" 2>/dev/null
sed -i '/bash_completion/d' "$HOME/.bashrc" "$HOME/.zshrc" "$HOME/.profile" 2>/dev/null
print_success "NVM and associated Node.js versions removed."
print_warning "You may need to manually remove any remaining Node.js related binaries from your PATH if they were installed globally outside NVM."
else
print_info "NVM directory '$HOME/.nvm' not found. Nothing to uninstall."
fi
sleep 1
}
remove_sudoers_file() {
print_info "--- Removing Sudoers Configuration ---"
sleep 1
if [ -f "$SUDOERS_FILE" ]; then
confirm_action "Do you want to remove the sudoers file '$SUDOERS_FILE' created for CandyPanel permissions? This will revoke specific passwordless sudo access for the CandyPanel user."
print_info "Removing sudoers file: $SUDOERS_FILE..."
sudo rm "$SUDOERS_FILE" || { print_error "Failed to remove sudoers file. Manual removal might be needed."; exit 1; }
print_success "Sudoers file removed."
else
print_info "Sudoers file '$SUDOERS_FILE' not found. Nothing to remove."
fi
sleep 1
}
uninstall_wireguard() {
print_info "--- Uninstalling WireGuard and its Configurations ---"
sleep 1
confirm_action "Do you want to uninstall WireGuard and remove its configuration files? This will remove all VPN configurations."
print_info "Attempting to stop all active WireGuard interfaces..."
for conf_file in /etc/wireguard/*.conf; do
if [ -f "$conf_file" ]; then
local interface_name=$(basename "$conf_file" .conf)
print_info "Stopping WireGuard interface: $interface_name..."
sudo wg-quick down "$interface_name" > /dev/null 2>&1 || print_warning "Could not stop WireGuard interface '$interface_name'. It might not be active or already stopped."
sudo systemctl disable "wg-quick@${interface_name}.service" > /dev/null 2>&1 || print_warning "Could not disable WireGuard service for '$interface_name'. It might not be enabled."
sudo rm -f "/etc/systemd/system/wg-quick@${interface_name}.service" > /dev/null 2>&1
fi
done
print_success "Attempted to stop and disable WireGuard interfaces."
print_info "Removing WireGuard packages (wireguard and wireguard-tools)..."
if command -v apt &> /dev/null; then
sudo apt purge -y wireguard wireguard-tools || print_warning "Failed to purge WireGuard packages. They might not be installed or require manual removal."
elif command -v dnf &> /dev/null; then
sudo dnf remove -y wireguard-tools || print_warning "Failed to remove WireGuard packages. They might not be installed or require manual removal."
elif command -v pacman &> /dev/null; then
sudo pacman -Rs --noconfirm wireguard-tools || print_warning "Failed to remove WireGuard packages. They might not be installed or require manual removal."
else
print_warning "Package manager not recognized. Please manually uninstall 'wireguard' and 'wireguard-tools' packages."
fi
print_success "WireGuard packages removal attempt complete."
print_info "Removing WireGuard configuration directory: /etc/wireguard/..."
if [ -d "/etc/wireguard/" ]; then
sudo rm -rf "/etc/wireguard/" || { print_error "Failed to remove /etc/wireguard/. Check permissions."; }
print_success "WireGuard configuration directory removed."
else
print_info "/etc/wireguard/ directory not found. Nothing to remove."
fi
print_info "Removing WireGuard connections from NetworkManager (if any)..."
if command -v nmcli &> /dev/null; then
local wg_connections=$(nmcli -t -f UUID,TYPE connection show --active | grep 'wireguard' | cut -d':' -f1)
if [ -n "$wg_connections" ]; then
for uuid in $wg_connections; do
print_info "Deleting NetworkManager WireGuard connection (UUID: $uuid)..."
sudo nmcli connection delete uuid "$uuid" || print_warning "Failed to delete NetworkManager WireGuard connection $uuid."
done
print_success "NetworkManager WireGuard connections removed."
else
print_info "No active WireGuard connections found in NetworkManager."
fi
else
print_info "nmcli (NetworkManager CLI) not found. Skipping NetworkManager cleanup."
fi
print_info "Reloading Systemd daemon after WireGuard cleanup..."
sudo systemctl daemon-reload || { print_warning "Failed to reload Systemd daemon. This might not be critical."; }
print_success "Systemd daemon reloaded."
sleep 2
}
# --- Main Install/Update/Uninstall Logic ---
run_install() {
print_header "Candy Panel Deployment Script"
confirm_action "This script will deploy your Candy panel with Flask serving both frontend and backend. Ensure you have updated the REPO_URL variable in the script."
check_prerequisites
setup_permissions
install_nodejs_with_nvm
clone_or_update_repo
# Prompt for IPv6 information
local ipv6_address_range
local ipv6_dns
read -p "$(echo -e "${YELLOW}INPUT:${RESET} Do you want to enable IPv6 support? (y/N)? ")" -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
read -p "$(echo -e "${YELLOW}INPUT:${RESET} Enter IPv6 Address Range for WireGuard clients (e.g., fd86:ea04:1115::1/64): ")" ipv6_address_range
read -p "$(echo -e "${YELLOW}INPUT:${RESET} Enter IPv6 DNS Server (e.g., 2001:4860:4860::8888): ")" ipv6_dns
fi
deploy_backend
deploy_frontend
configure_frontend_api_url
configure_firewall
echo -e "\n${BOLD}${GREEN}====================================================${RESET}"
echo-e "${BOLD}${GREEN} Deployment Complete! ${RESET}"
echo -e "${BOLD}${GREEN}====================================================${RESET}"
echo -e "${BOLD}${GREEN} Your Candy Panel should now be accessible at:${RESET}"
echo -e "${BOLD}${GREEN} http://YOUR_SERVER_IP:$BACKEND_PORT${RESET}"
print_warning "Remember to replace YOUR_SERVER_IP with your actual server's public IP address."
print_warning "Note: SSL is NOT configured with this setup. For HTTPS, you will need to add a reverse proxy like Nginx or Caddy."
echo -e "${BOLD}${GREEN}====================================================${RESET}\n"
print_info "Ensure the Linux user '$LINUX_USER' has appropriate permissions for WireGuard operations."
print_info "Flask application is running on port $BACKEND_PORT and serving all content."
}
# A separate function for backend deployment to pass the new variables
deploy_backend() {
print_info "--- Deploying Flask Backend ---"
sleep 1
print_info "Navigating to backend directory: $BACKEND_DIR"
cd "$BACKEND_DIR" || { print_error "Backend directory not found: $BACKEND_DIR"; exit 1; }
print_info "Creating and activating Python virtual environment..."
# Use the discovered Python executable
python3 -m venv venv || { print_error "Failed to create virtual environment."; exit 1; }
source venv/bin/activate || { print_error "Failed to activate virtual environment."; exit 1; }
print_success "Virtual environment activated."
sleep 1
print_info "Installing Python dependencies (Flask etc.)..."
# Install netifaces with required build dependencies if needed
pip install pyrogram flask[async] requests flask_cors psutil httpx tgcrypto nanoid || { print_error "Failed to install Python dependencies."; exit 1; }
print_info "Attempting to install netifaces specifically, including build dependencies..."
# Try installing netifaces with potential build dependencies for different distros
if command -v apt &> /dev/null; then
sudo apt install -y python3-netifaces || { print_error "Failed to install netifaces. Check build-essential and python3-dev installations."; exit 1; }
pip install netifaces || { print_error "Failed to install netifaces. Check build-essential and python3-dev installations."; exit 1; }
elif command -v yum &> /dev/null; then
sudo yum install -y python3-netifaces || { print_error "Failed to install netifaces. Check build-essential and python3-devel installations."; exit 1; }
pip install netifaces || { print_error "Failed to install netifaces. Check build-essential and python3-dev installations."; exit 1; }
else
pip install netifaces || print_warning "Failed to install netifaces. Please install it manually with appropriate system headers if needed."