forked from PatchMon/PatchMon
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.sh
More file actions
executable file
·3546 lines (2932 loc) · 128 KB
/
setup.sh
File metadata and controls
executable file
·3546 lines (2932 loc) · 128 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
# PatchMon Self-Hosting Installation Script
# Automated deployment script for self-hosted PatchMon instances
# Usage: ./self-hosting-install.sh
# Interactive self-hosting installation script
set -e
# Create main installation log file
INSTALL_LOG="/var/log/patchmon-install.log"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] === PatchMon Self-Hosting Installation Started ===" >> "$INSTALL_LOG"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Script PID: $$" >> "$INSTALL_LOG"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Running as user: $(whoami)" >> "$INSTALL_LOG"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Current directory: $(pwd)" >> "$INSTALL_LOG"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Script arguments: $@" >> "$INSTALL_LOG"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Script path: $0" >> "$INSTALL_LOG"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] ======================================" >> "$INSTALL_LOG"
# Create immediate debug log for troubleshooting
DEBUG_LOG="/tmp/patchmon_debug_$(date +%Y%m%d_%H%M%S).log"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] === PatchMon Script Started ===" >> "$DEBUG_LOG"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Script PID: $$" >> "$DEBUG_LOG"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Running as user: $(whoami)" >> "$DEBUG_LOG"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Current directory: $(pwd)" >> "$DEBUG_LOG"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Script arguments: $@" >> "$DEBUG_LOG"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Script path: $0" >> "$DEBUG_LOG"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] ======================================" >> "$DEBUG_LOG"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Global variables
SCRIPT_VERSION="self-hosting-install.sh v1.4.2-selfhost-2026-02-18"
DEFAULT_GITHUB_REPO="https://github.com/PatchMon/PatchMon.git"
FQDN=""
CUSTOM_FQDN=""
EMAIL=""
# Logging function
function log_message() {
local message="$1"
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
local log_file="/var/log/patchmon-install.log"
echo "[${timestamp}] ${message}" >> "$log_file"
echo "[${timestamp}] ${message}"
}
DEPLOYMENT_BRANCH="main"
GITHUB_REPO=""
DB_SAFE_NAME=""
DB_PASS=""
JWT_SECRET=""
BACKEND_PORT=""
APP_DIR=""
USE_LETSENCRYPT="false" # Will be set based on user input
SERVER_PROTOCOL_SEL="https"
SERVER_PORT_SEL="" # Will be set to BACKEND_PORT in init_instance_vars
# Port that appears in the browser URL (e.g. 1234 when NAT 1234→80). Empty = use default (443/https or backend port/http).
CORS_URL_PORT=""
SETUP_NGINX="true"
UPDATE_MODE="false"
SELECTED_INSTANCE=""
SELECTED_SERVICE_NAME=""
# Functions
print_status() {
printf "${GREEN}%s${NC}\n" "$1"
}
print_info() {
printf "${BLUE}%s${NC}\n" "$1"
}
print_error() {
printf "${RED}%s${NC}\n" "$1"
}
print_warning() {
printf "${YELLOW}%s${NC}\n" "$1"
}
print_question() {
printf "${BLUE}%s${NC}\n" "$1"
}
print_success() {
printf "${GREEN}%s${NC}\n" "$1"
}
# Interactive input functions
read_input() {
local prompt="$1"
local var_name="$2"
local default_value="$3"
if [ -n "$default_value" ]; then
echo -n -e "${BLUE}$prompt${NC} [${YELLOW}$default_value${NC}]: "
else
echo -n -e "${BLUE}$prompt${NC}: "
fi
read -r input
if [ -z "$input" ] && [ -n "$default_value" ]; then
eval "$var_name='$default_value'"
else
eval "$var_name='$input'"
fi
}
read_yes_no() {
local prompt="$1"
local var_name="$2"
local default_value="$3"
while true; do
if [ -n "$default_value" ]; then
echo -n -e "${BLUE}$prompt${NC} [${YELLOW}$default_value${NC}]: "
else
echo -n -e "${BLUE}$prompt${NC} (y/n): "
fi
read -r input
if [ -z "$input" ] && [ -n "$default_value" ]; then
input="$default_value"
fi
case $input in
[Yy]|[Yy][Ee][Ss])
eval "$var_name='y'"
break
;;
[Nn]|[Nn][Oo])
eval "$var_name='n'"
break
;;
*)
print_error "Please answer yes (y) or no (n)"
;;
esac
done
}
print_banner() {
echo -e "${BLUE}====================================================${NC}"
echo -e "${BLUE} PatchMon Self-Hosting Installation${NC}"
echo -e "${BLUE}Running: $SCRIPT_VERSION${NC}"
echo -e "${BLUE}====================================================${NC}"
}
# Interactive setup functions
check_timezone() {
print_info "Checking current timezone..."
current_tz=$(timedatectl show --property=Timezone --value 2>/dev/null || echo "Unknown")
if [ "$current_tz" != "Unknown" ]; then
current_datetime=$(date)
print_info "Current timezone: $current_tz"
print_info "Current date/time: $current_datetime"
read_yes_no "Is this timezone and date/time correct?" TIMEZONE_CORRECT "y"
if [ "$TIMEZONE_CORRECT" = "n" ]; then
print_info "Available timezones:"
timedatectl list-timezones | head -20
print_warning "Showing first 20 timezones. Use 'timedatectl list-timezones' to see all."
read_input "Enter your timezone (e.g., America/New_York, Europe/London)" NEW_TIMEZONE
if [ -n "$NEW_TIMEZONE" ]; then
print_info "Setting timezone to $NEW_TIMEZONE..."
timedatectl set-timezone "$NEW_TIMEZONE"
print_status "Timezone updated to $NEW_TIMEZONE"
# Show updated date/time
updated_datetime=$(date)
print_info "Updated date/time: $updated_datetime"
fi
fi
else
print_warning "Could not detect timezone. Please set it manually if needed."
current_datetime=$(date)
print_info "Current date/time: $current_datetime"
fi
}
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
}
# Function to run commands as a specific user with better error handling
run_as_user() {
local user="$1"
local command="$2"
if ! command -v sudo >/dev/null 2>&1; then
print_error "sudo is required but not installed. Please install sudo first."
exit 1
fi
if ! id "$user" &>/dev/null; then
print_error "User '$user' does not exist"
exit 1
fi
sudo -u "$user" bash -c "$command"
}
# Detect and use the best available package manager
detect_package_manager() {
# Prefer apt over apt-get for modern Debian/Ubuntu systems
if command -v apt >/dev/null 2>&1; then
PKG_MANAGER="apt"
PKG_UPDATE="apt update"
PKG_UPGRADE="apt upgrade -y"
PKG_INSTALL="apt install -y"
elif command -v apt-get >/dev/null 2>&1; then
PKG_MANAGER="apt-get"
PKG_UPDATE="apt-get update"
PKG_UPGRADE="apt-get upgrade -y"
PKG_INSTALL="apt-get install -y"
else
print_error "No supported package manager found (apt or apt-get required)"
print_info "This script requires a Debian/Ubuntu-based system"
exit 1
fi
print_info "Using package manager: $PKG_MANAGER"
}
check_prerequisites() {
print_info "Running and checking prerequisites..."
# Check if running as root
check_root
# Detect package manager
detect_package_manager
print_info "Installing updates..."
$PKG_UPDATE -y
$PKG_UPGRADE
print_info "Installing prerequisite applications..."
# Install sudo if not present (needed for user switching)
if ! command -v sudo >/dev/null 2>&1; then
print_info "Installing sudo (required for user switching)..."
$PKG_INSTALL sudo
fi
$PKG_INSTALL wget curl jq git netcat-openbsd
print_status "Prerequisites installed successfully"
}
select_branch() {
print_info "Fetching available releases from GitHub repository..."
# Create temporary directory for git operations
TEMP_DIR="/tmp/patchmon_branches_$$"
mkdir -p "$TEMP_DIR"
cd "$TEMP_DIR"
# Try to clone the repository normally
if git clone "$DEFAULT_GITHUB_REPO" . 2>/dev/null; then
# Get list of tags sorted by version (semantic versioning)
# Using git tag with version sorting
tags=$(git tag -l --sort=-v:refname 2>/dev/null | head -3)
if [ -n "$tags" ]; then
print_info "Available releases and branches:"
echo ""
# Display last 3 release tags
option_count=1
declare -A options_map
while IFS= read -r tag; do
if [ -n "$tag" ]; then
# Get tag date and commit info
tag_date=$(git log -1 --format="%ci" "$tag" 2>/dev/null || echo "Unknown")
# Format the date
if [ "$tag_date" != "Unknown" ]; then
formatted_date=$(date -d "$tag_date" "+%Y-%m-%d %H:%M" 2>/dev/null || echo "$tag_date")
else
formatted_date="Unknown"
fi
# Mark the first one as latest
if [ $option_count -eq 1 ]; then
printf "%2d. %-20s (Latest Release - %s)\n" "$option_count" "$tag" "$formatted_date"
else
printf "%2d. %-20s (Release - %s)\n" "$option_count" "$tag" "$formatted_date"
fi
# Store the tag for later selection
options_map[$option_count]="$tag"
option_count=$((option_count + 1))
fi
done <<< "$tags"
# Add main branch as an option
main_commit=$(git log -1 --format="%ci" "origin/main" 2>/dev/null || echo "Unknown")
if [ "$main_commit" != "Unknown" ]; then
formatted_main_date=$(date -d "$main_commit" "+%Y-%m-%d %H:%M" 2>/dev/null || echo "$main_commit")
else
formatted_main_date="Unknown"
fi
printf "%2d. %-20s (Development Branch - %s)\n" "$option_count" "main" "$formatted_main_date"
options_map[$option_count]="main"
echo ""
# Default to option 1 (latest release tag)
default_option=1
while true; do
read_input "Select version/branch number" SELECTION_NUMBER "$default_option"
if [[ "$SELECTION_NUMBER" =~ ^[0-9]+$ ]]; then
selected_option="${options_map[$SELECTION_NUMBER]}"
if [ -n "$selected_option" ]; then
DEPLOYMENT_BRANCH="$selected_option"
# Show confirmation
if [ "$selected_option" = "main" ]; then
print_status "Selected branch: main (latest development code)"
print_info "Last commit: $formatted_main_date"
else
print_status "Selected release: $selected_option"
tag_date=$(git log -1 --format="%ci" "$selected_option" 2>/dev/null || echo "Unknown")
if [ "$tag_date" != "Unknown" ]; then
formatted_date=$(date -d "$tag_date" "+%Y-%m-%d %H:%M" 2>/dev/null || echo "$tag_date")
print_info "Release date: $formatted_date"
fi
fi
break
else
print_error "Invalid selection number. Please try again."
fi
else
print_error "Please enter a valid number."
fi
done
else
print_warning "No release tags found, using default: main"
DEPLOYMENT_BRANCH="main"
fi
else
print_warning "Could not connect to GitHub repository"
print_warning "This might be due to:"
print_warning " • Network connectivity issues"
print_warning " • Firewall blocking git access"
print_warning " • GitHub repository access restrictions"
print_warning "Using default branch: main"
DEPLOYMENT_BRANCH="main"
fi
# Clean up
cd /
rm -rf "$TEMP_DIR"
}
interactive_setup() {
print_banner
print_info "Welcome to PatchMon Self-Hosting Installation!"
print_info "This script will guide you through the installation process."
echo ""
# Check prerequisites
check_prerequisites
echo ""
# Check timezone
check_timezone
echo ""
# Get basic information
print_question "Let's gather some information about your installation:"
echo ""
read_input "Enter your domain name or IP address (e.g., patchmon.yourdomain.com or 192.168.1.100)" FQDN "patchmon.internal"
echo ""
print_info "🔒 SSL/HTTPS Configuration:"
print_info " • Public hosting (accessible from internet): Enable SSL for security"
print_info " • Local hosting (internal network only): SSL not required"
echo ""
read_yes_no "Are you hosting this publicly on the internet and want SSL/HTTPS with Let's Encrypt?" SSL_ENABLED "n"
if [ "$SSL_ENABLED" = "y" ]; then
read_input "Enter your email address for Let's Encrypt SSL certificate" EMAIL
else
EMAIL=""
fi
echo ""
print_info "Port in browser URL (optional):"
print_info " • If users reach the dashboard via a custom port (e.g. firewall NAT 1234→80), enter that port."
print_info " • Leave blank for default: 443 (HTTPS) or backend port (HTTP direct)."
read_input "Port number in browser URL (blank for default)" CORS_URL_PORT ""
# Select branch
echo ""
select_branch
echo ""
# Confirm settings
print_info "Please confirm your settings:"
echo " Domain/IP: $FQDN"
echo " SSL Enabled: $SSL_ENABLED"
if [ "$SSL_ENABLED" = "y" ]; then
echo " Email: $EMAIL"
fi
if [ -n "$CORS_URL_PORT" ]; then
echo " Port in browser URL: $CORS_URL_PORT"
fi
echo " Branch: $DEPLOYMENT_BRANCH"
echo ""
read_yes_no "Proceed with installation?" CONFIRM_INSTALL "y"
if [ "$CONFIRM_INSTALL" = "n" ]; then
print_info "Installation cancelled by user."
exit 0
fi
print_success "Starting installation process..."
echo ""
}
# Generate random password
generate_password() {
openssl rand -base64 32 | tr -d "=+/" | cut -c1-25
}
# Generate JWT secret
generate_jwt_secret() {
openssl rand -base64 64 | tr -d "=+/" | cut -c1-50
}
# Generate Redis password
generate_redis_password() {
openssl rand -base64 32 | tr -d "=+/" | cut -c1-25
}
# Find next available Redis database
find_next_redis_db() {
print_info "Finding next available Redis database..." >&2
# Start from database 0 and keep checking until we find an empty one
local db_num=0
local max_attempts=16 # Redis default is 16 databases
# Check if Redis requires authentication
local test_output
test_output=$(redis-cli -h localhost -p 6379 ping 2>&1)
# Determine auth requirements
local auth_required=false
local redis_auth_args=""
if echo "$test_output" | grep -q "NOAUTH\|WRONGPASS"; then
auth_required=true
# Try to load admin credentials if ACL file exists
if [ -f /etc/redis/users.acl ] && grep -q "^user admin" /etc/redis/users.acl; then
# Redis is configured with ACL - try to extract admin password
print_info "Redis requires authentication, attempting with admin credentials..." >&2
# For multi-instance setups, we can't know the admin password yet
# So we'll just use database 0 as default
print_info "Using database 0 (Redis ACL already configured)" >&2
echo "0"
return 0
fi
fi
while [ $db_num -lt $max_attempts ]; do
# Test if database is empty
local key_count
local redis_output
# Try to get database size (with or without auth)
redis_output=$(redis-cli -h localhost -p 6379 -n "$db_num" DBSIZE 2>&1)
# Check for authentication errors
if echo "$redis_output" | grep -q "NOAUTH\|WRONGPASS"; then
# If we hit auth errors and haven't configured yet, use database 0
print_info "Redis requires authentication, defaulting to database 0" >&2
echo "0"
return 0
fi
# Check for other errors
if echo "$redis_output" | grep -q "ERR"; then
if echo "$redis_output" | grep -q "invalid DB index"; then
print_warning "Reached maximum database limit at database $db_num" >&2
break
else
print_error "Error checking database $db_num: $redis_output" >&2
return 1
fi
fi
key_count="$redis_output"
# If database is empty, use it
if [ "$key_count" = "0" ] || [ "$key_count" = "(integer) 0" ]; then
print_status "Found available Redis database: $db_num (empty)" >&2
echo "$db_num"
return 0
fi
print_info "Database $db_num has $key_count keys, checking next..." >&2
db_num=$((db_num + 1))
done
print_warning "No available Redis databases found (checked 0-$max_attempts)" >&2
print_info "Using database 0 (may have existing data)" >&2
echo "0"
return 0
}
# Initialize instance variables
init_instance_vars() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] init_instance_vars function started" >> "$DEBUG_LOG"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Creating safe database name from FQDN: $FQDN" >> "$DEBUG_LOG"
# Create safe database name from FQDN
DB_SAFE_NAME=$(echo "$FQDN" | sed 's/[^a-zA-Z0-9]/_/g' | sed 's/^_*//' | sed 's/_*$//')
# Check if FQDN starts with a digit (likely an IP address)
if [[ "$FQDN" =~ ^[0-9] ]]; then
# Generate 2 random letters for IP address prefixing
RANDOM_PREFIX=$(tr -dc 'a-z' < /dev/urandom | head -c 2)
DB_SAFE_NAME="${RANDOM_PREFIX}${DB_SAFE_NAME}"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] IP address detected, prefixed with: $RANDOM_PREFIX" >> "$DEBUG_LOG"
print_info "IP address detected ($FQDN), using prefix '$RANDOM_PREFIX' for database/service names"
fi
DB_NAME="${DB_SAFE_NAME}"
DB_USER="${DB_SAFE_NAME}"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] DB_SAFE_NAME: $DB_SAFE_NAME" >> "$DEBUG_LOG"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] DB_NAME: $DB_NAME" >> "$DEBUG_LOG"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] DB_USER: $DB_USER" >> "$DEBUG_LOG"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Generating password..." >> "$DEBUG_LOG"
DB_PASS=$(generate_password)
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Generating JWT secret..." >> "$DEBUG_LOG"
JWT_SECRET=$(generate_jwt_secret)
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Generating Redis password..." >> "$DEBUG_LOG"
REDIS_PASSWORD=$(generate_redis_password)
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Finding next available Redis database..." >> "$DEBUG_LOG"
REDIS_DB=$(find_next_redis_db)
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Generating random backend port..." >> "$DEBUG_LOG"
# Generate random backend port (3001-3999)
BACKEND_PORT=$((3001 + RANDOM % 999))
# Set SERVER_PORT_SEL to 443 for HTTPS (external port) or backend port for HTTP
if [ "$SERVER_PROTOCOL_SEL" = "https" ]; then
SERVER_PORT_SEL=443
else
SERVER_PORT_SEL=$BACKEND_PORT
fi
echo "[$(date '+%Y-%m-%d %H:%M:%S')] BACKEND_PORT: $BACKEND_PORT" >> "$DEBUG_LOG"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] SERVER_PORT_SEL: $SERVER_PORT_SEL" >> "$DEBUG_LOG"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Setting application directory and service name..." >> "$DEBUG_LOG"
# Set application directory and service name
APP_DIR="/opt/${FQDN}"
SERVICE_NAME="${FQDN}"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] APP_DIR: $APP_DIR" >> "$DEBUG_LOG"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] SERVICE_NAME: $SERVICE_NAME" >> "$DEBUG_LOG"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Creating dedicated user name..." >> "$DEBUG_LOG"
# Create dedicated user name (safe for system users)
INSTANCE_USER=$(echo "$DB_SAFE_NAME" | cut -c1-32)
echo "[$(date '+%Y-%m-%d %H:%M:%S')] INSTANCE_USER: $INSTANCE_USER" >> "$DEBUG_LOG"
print_info "Initialized variables for $FQDN"
print_info "Database: $DB_NAME"
print_info "Backend Port: $BACKEND_PORT"
print_info "App Directory: $APP_DIR"
print_info "Instance User: $INSTANCE_USER"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] init_instance_vars function completed successfully" >> "$DEBUG_LOG"
}
# Update system packages
update_system() {
print_info "Updating system packages..."
$PKG_UPDATE -y
$PKG_UPGRADE
}
# Install essential tools
install_essential_tools() {
print_info "Installing essential tools..."
$PKG_INSTALL curl netcat-openbsd git jq
}
# Install Node.js (if not already installed)
install_nodejs() {
# Force PATH refresh to ensure we get the latest Node.js
export PATH="/usr/bin:/usr/local/bin:$PATH"
hash -r # Clear bash command cache
NODE_VERSION=""
if command -v node >/dev/null 2>&1; then
NODE_VERSION=$(node --version 2>/dev/null | sed 's/v//')
print_info "Node.js already installed: v$NODE_VERSION"
# Check if version is 18 or higher
if [ "$(echo "$NODE_VERSION" | cut -d. -f1)" -ge 18 ]; then
print_status "Node.js version is sufficient (v$NODE_VERSION)"
# Clean npm cache to avoid issues
npm cache clean --force 2>/dev/null || true
return 0
else
print_warning "Node.js version $NODE_VERSION is too old, updating..."
fi
fi
print_info "Installing Node.js 20.x..."
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
$PKG_INSTALL nodejs
# Verify installation
NODE_VERSION=$(node --version | sed 's/v//')
NPM_VERSION=$(npm --version)
print_status "Node.js installed: v$NODE_VERSION"
print_status "npm installed: v$NPM_VERSION"
# Clean npm cache to avoid issues
npm cache clean --force 2>/dev/null || true
}
# Install PostgreSQL
install_postgresql() {
print_info "Installing PostgreSQL..."
if systemctl is-active --quiet postgresql; then
print_status "PostgreSQL already running"
else
$PKG_INSTALL postgresql postgresql-contrib
systemctl start postgresql
systemctl enable postgresql
print_status "PostgreSQL installed and started"
fi
}
# Install Redis
install_redis() {
print_info "Installing Redis..."
if systemctl is-active --quiet redis-server; then
print_status "Redis already running"
else
$PKG_INSTALL redis-server
systemctl start redis-server
systemctl enable redis-server
print_status "Redis installed and started"
fi
}
# Configure Redis with user authentication
configure_redis() {
print_info "Configuring Redis with user authentication..."
# Check if Redis is running
if ! systemctl is-active --quiet redis-server; then
print_error "Redis is not running. Please start Redis first."
return 1
fi
# Generate Redis username based on instance (global variable for use in create_env_files)
REDIS_USER="patchmon_${DB_SAFE_NAME}"
# Generate separate user password (more secure than reusing admin password)
# This will be stored in the .env file for the application to use
REDIS_USER_PASSWORD=$(openssl rand -base64 32 | tr -d "=+/" | cut -c1-32)
print_info "Creating Redis user: $REDIS_USER for database $REDIS_DB"
# Create Redis configuration backup
if [ -f /etc/redis/redis.conf ]; then
cp /etc/redis/redis.conf /etc/redis/redis.conf.backup.$(date +%Y%m%d_%H%M%S)
print_info "Created Redis configuration backup"
fi
# Configure Redis with ACL authentication
print_info "Configuring Redis with ACL authentication"
# Ensure ACL file exists and is configured
if [ ! -f /etc/redis/users.acl ]; then
touch /etc/redis/users.acl
chown redis:redis /etc/redis/users.acl
chmod 640 /etc/redis/users.acl
print_status "Created Redis ACL file"
else
# Backup existing ACL file
cp /etc/redis/users.acl /etc/redis/users.acl.backup.$(date +%Y%m%d_%H%M%S) 2>/dev/null || true
print_info "Backed up existing ACL file"
fi
# Configure ACL file in redis.conf
if ! grep -q "^aclfile" /etc/redis/redis.conf; then
echo "aclfile /etc/redis/users.acl" >> /etc/redis/redis.conf
print_status "Added ACL file configuration to Redis"
fi
# Remove any requirepass configuration (incompatible with ACL)
if grep -q "^requirepass" /etc/redis/redis.conf; then
sed -i 's/^requirepass.*/# &/' /etc/redis/redis.conf
print_status "Disabled requirepass (incompatible with ACL)"
fi
# Remove any user definitions from redis.conf (should be in ACL file)
if grep -q "^user " /etc/redis/redis.conf; then
sed -i '/^user /d' /etc/redis/redis.conf
print_status "Removed user definitions from redis.conf"
fi
# Create or update admin user in ACL file
if grep -q "^user admin" /etc/redis/users.acl; then
print_info "Admin user already exists in ACL, updating password..."
# Remove old admin line and add new one
sed -i '/^user admin/d' /etc/redis/users.acl
echo "user admin on sanitize-payload >$REDIS_PASSWORD ~* &* +@all" >> /etc/redis/users.acl
print_status "Updated admin user password"
else
echo "user admin on sanitize-payload >$REDIS_PASSWORD ~* &* +@all" >> /etc/redis/users.acl
print_status "Added admin user to ACL file"
fi
# Restart Redis to apply ACL configuration
print_info "Restarting Redis to apply ACL configuration..."
systemctl restart redis-server
# Wait for Redis to start with retry logic
sleep 5
# Test admin connection with retries
local max_retries=3
local retry=0
local admin_works=false
while [ $retry -lt $max_retries ]; do
if redis-cli -h 127.0.0.1 -p 6379 --user admin --pass "$REDIS_PASSWORD" --no-auth-warning ping > /dev/null 2>&1; then
admin_works=true
break
fi
print_info "Waiting for Redis to be ready... (attempt $((retry + 1))/$max_retries)"
sleep 2
retry=$((retry + 1))
done
if [ "$admin_works" = false ]; then
print_error "Failed to verify admin connection after Redis restart"
print_error "Redis ACL configuration may have issues"
# Try to fix by disabling ACL and using requirepass instead
print_warning "Attempting fallback: using requirepass instead of ACL..."
sed -i 's/^aclfile/# aclfile/' /etc/redis/redis.conf
sed -i "s/^# requirepass .*/requirepass $REDIS_PASSWORD/" /etc/redis/redis.conf
if ! grep -q "^requirepass" /etc/redis/redis.conf; then
echo "requirepass $REDIS_PASSWORD" >> /etc/redis/redis.conf
fi
systemctl restart redis-server
sleep 3
# Test requirepass
if redis-cli -h 127.0.0.1 -p 6379 -a "$REDIS_PASSWORD" --no-auth-warning ping > /dev/null 2>&1; then
print_status "Fallback successful - using requirepass authentication"
# For requirepass mode, we'll set REDIS_USER empty later
print_info "Note: Using legacy requirepass mode instead of ACL"
else
print_error "Fallback also failed - Redis authentication is broken"
return 1
fi
else
print_status "Redis ACL authentication configuration successful"
fi
# Create Redis user with ACL (only if admin_works, meaning we're using ACL mode)
if [ "$admin_works" = true ]; then
print_info "Creating Redis ACL user: $REDIS_USER"
# Create user with password and permissions - capture output for error handling
local acl_result
acl_result=$(redis-cli -h 127.0.0.1 -p 6379 --user admin --pass "$REDIS_PASSWORD" --no-auth-warning ACL SETUSER "$REDIS_USER" on ">${REDIS_USER_PASSWORD}" ~* +@all 2>&1)
if [ "$acl_result" = "OK" ]; then
print_status "Redis user '$REDIS_USER' created successfully"
# Save ACL users to file to persist across restarts
local save_result
save_result=$(redis-cli -h 127.0.0.1 -p 6379 --user admin --pass "$REDIS_PASSWORD" --no-auth-warning ACL SAVE 2>&1)
if [ "$save_result" = "OK" ]; then
print_status "Redis ACL users saved to file"
else
print_warning "Failed to save ACL users to file: $save_result"
fi
# Verify user was actually created
local verify_result
verify_result=$(redis-cli -h 127.0.0.1 -p 6379 --user admin --pass "$REDIS_PASSWORD" --no-auth-warning ACL GETUSER "$REDIS_USER" 2>&1)
if [ "$verify_result" = "(nil)" ]; then
print_error "User creation reported OK but user does not exist"
return 1
fi
# Test user connection
print_info "Testing Redis user connection..."
if redis-cli -h 127.0.0.1 -p 6379 --user "$REDIS_USER" --pass "$REDIS_USER_PASSWORD" --no-auth-warning -n "$REDIS_DB" ping > /dev/null 2>&1; then
print_status "Redis user connection test successful"
else
print_error "Redis user connection test failed"
return 1
fi
# Mark the selected database as in-use
redis-cli -h 127.0.0.1 -p 6379 --user "$REDIS_USER" --pass "$REDIS_USER_PASSWORD" --no-auth-warning -n "$REDIS_DB" SET "patchmon:initialized" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > /dev/null
print_status "Marked Redis database $REDIS_DB as in-use"
else
print_error "Failed to create Redis user: $acl_result"
return 1
fi
else
# Using requirepass mode - no per-user ACL
print_info "Using requirepass mode - testing connection..."
# For requirepass, we don't use username, just password
if redis-cli -h 127.0.0.1 -p 6379 -a "$REDIS_PASSWORD" --no-auth-warning -n "$REDIS_DB" ping > /dev/null 2>&1; then
print_status "Redis requirepass connection test successful"
# Mark the selected database as in-use
redis-cli -h 127.0.0.1 -p 6379 -a "$REDIS_PASSWORD" --no-auth-warning -n "$REDIS_DB" SET "patchmon:initialized" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > /dev/null
print_status "Marked Redis database $REDIS_DB as in-use"
# Set REDIS_USER to empty for requirepass mode
REDIS_USER=""
REDIS_USER_PASSWORD="$REDIS_PASSWORD"
else
print_error "Redis requirepass connection test failed"
return 1
fi
fi
# Note: Redis credentials will be written to .env by create_env_files() function
print_status "Redis configured successfully"
if [ -n "$REDIS_USER" ]; then
print_info "Redis Mode: ACL with user '$REDIS_USER'"
else
print_info "Redis Mode: requirepass (legacy single-password auth)"
fi
print_info "Redis credentials will be saved to backend/.env"
return 0
}
# Install nginx
install_nginx() {
print_info "Installing nginx..."
if systemctl is-active --quiet nginx; then
print_status "nginx already running"
else
$PKG_INSTALL nginx
systemctl start nginx
systemctl enable nginx
print_status "nginx installed and started"
fi
}
# Install certbot for Let's Encrypt
install_certbot() {
print_info "Installing certbot for Let's Encrypt..."
if command -v certbot >/dev/null 2>&1; then
print_status "certbot already installed"
else
$PKG_INSTALL certbot python3-certbot-nginx
print_status "certbot installed"
fi
}
# Create dedicated user for this instance
create_instance_user() {
print_info "Creating dedicated user: $INSTANCE_USER"
# Create application directory first (as root)
mkdir -p "$APP_DIR"
# Check if user already exists
if id "$INSTANCE_USER" &>/dev/null; then
print_warning "User $INSTANCE_USER already exists, skipping creation"
# Ensure directory ownership is correct for existing user
chown -R "$INSTANCE_USER:$INSTANCE_USER" "$APP_DIR"
chmod 755 "$APP_DIR"
return 0
fi
# Create user with no login shell and no home directory
useradd --system --no-create-home --shell /bin/false "$INSTANCE_USER"
# Set ownership and permissions
chown -R "$INSTANCE_USER:$INSTANCE_USER" "$APP_DIR"
chmod 755 "$APP_DIR"
print_status "Dedicated user $INSTANCE_USER created successfully"
}
# Setup Node.js environment isolation for this instance
setup_nodejs_isolation() {
print_info "Setting up Node.js environment isolation for $INSTANCE_USER..."
# Create npm directories as root first
mkdir -p "$APP_DIR/.npm" "$APP_DIR/.npm-global"
# Create .npmrc file with proper configuration
cat > "$APP_DIR/.npmrc" << EOF
cache=$APP_DIR/.npm
prefix=$APP_DIR/.npm-global
init-module=$APP_DIR/.npm-global/.npm-init.js
tmp=$APP_DIR/.npm/tmp
EOF
# Set ownership to the dedicated user
chown -R "$INSTANCE_USER:$INSTANCE_USER" "$APP_DIR/.npm" "$APP_DIR/.npm-global" "$APP_DIR/.npmrc"
print_status "Node.js environment isolation configured for $INSTANCE_USER"
}
# Setup database for instance
setup_database() {
print_info "Setting up database: $DB_NAME"
# Check if sudo is available for user switching
if command -v sudo >/dev/null 2>&1; then
# Check if user exists
user_exists=$(sudo -u postgres psql -tAc "SELECT 1 FROM pg_roles WHERE rolname='$DB_USER'" || echo "0")
if [ "$user_exists" = "1" ]; then
print_info "Database user $DB_USER already exists, skipping creation"
else
print_info "Creating database user $DB_USER"
sudo -u postgres psql -c "CREATE USER $DB_USER WITH PASSWORD '$DB_PASS';"
fi
# Check if database exists
db_exists=$(sudo -u postgres psql -tAc "SELECT 1 FROM pg_database WHERE datname='$DB_NAME'" || echo "0")
if [ "$db_exists" = "1" ]; then
print_info "Database $DB_NAME already exists, skipping creation"
else
print_info "Creating database $DB_NAME"
sudo -u postgres psql -c "CREATE DATABASE $DB_NAME OWNER $DB_USER;"
fi
# Always grant privileges (in case they were revoked)
sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;"
else
# Alternative method for systems without sudo (run as postgres user directly)
print_warning "sudo not available, using alternative method for PostgreSQL setup"
# Check if user exists
user_exists=$(su - postgres -c "psql -tAc \"SELECT 1 FROM pg_roles WHERE rolname='$DB_USER'\"" || echo "0")
if [ "$user_exists" = "1" ]; then
print_info "Database user $DB_USER already exists, skipping creation"
else
print_info "Creating database user $DB_USER"
su - postgres -c "psql -c \"CREATE USER $DB_USER WITH PASSWORD '$DB_PASS';\""
fi
# Check if database exists