-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathinstall.sh
More file actions
executable file
·1634 lines (1393 loc) · 55.5 KB
/
install.sh
File metadata and controls
executable file
·1634 lines (1393 loc) · 55.5 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
#######################################
# Aeterna - Dead Man's Switch
# One-Click Installation Script
#
# Security & Safety Features:
# - Atomic file operations (temp files + atomic moves)
# - Encryption key validation (format, length, permissions)
# - Comprehensive error handling with cleanup traps
# - Input validation and sanitization
# - Disk space checks before operations
# - Docker Compose file validation
# - Container startup verification
# - Graceful error recovery where possible
# - Detailed error messages for troubleshooting
#######################################
# Exit on error, but allow controlled error handling
# -e: Exit immediately if a command exits with non-zero status
# -u: Treat unset variables as an error
# -o pipefail: Return value of pipeline is last command to exit with non-zero
set -euo pipefail
# Trap errors and provide cleanup
cleanup_on_error() {
local exit_code=$?
# Disable trap to prevent recursive calls (error() calls exit which re-triggers ERR)
trap - ERR
if [ $exit_code -ne 0 ]; then
echo ""
echo -e "${RED}[✗]${NC} Installation failed (exit code $exit_code)"
echo "Check the error messages above for details."
echo "You may need to clean up manually: rm -rf ${INSTALL_DIR:-/opt/aeterna}"
fi
exit $exit_code
}
trap cleanup_on_error ERR
# Cleanup function for interrupted installations
cleanup_interrupt() {
echo ""
warning "Installation interrupted by user"
exit 130
}
trap cleanup_interrupt INT TERM
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
MAGENTA='\033[0;35m'
NC='\033[0m' # No Color
BOLD='\033[1m'
DIM='\033[2m'
# Script version
VERSION="1.3.0"
BRANCH="main" # Branch to checkout during installation
# Default values
PROXY_MODE="" # nginx or simple
PROXY_MODE_SET=false
# ASCII Art
print_banner() {
echo -e "${CYAN}"
echo " _ _ "
echo " / \ ___| |_ ___ _ __ _ __ __ _ "
echo " / _ \ / _ \ __/ _ \ '__| '_ \ / _\` |"
echo " / ___ \ __/ || __/ | | | | | (_| |"
echo "/_/ \_\___|\__\___|_| |_| |_|\__,_|"
echo ""
echo -e "${NC}${BOLD}Dead Man's Switch - Installation Wizard v${VERSION}${NC}"
echo ""
}
# Print colored messages
info() { echo -e "${BLUE}[INFO]${NC} $1"; }
success() { echo -e "${GREEN}[✓]${NC} $1"; }
warning() { echo -e "${YELLOW}[!]${NC} $1"; }
error() { echo -e "${RED}[✗]${NC} $1"; exit 1; }
step() { echo -e "${MAGENTA}[→]${NC} $1"; }
# Print help message
print_help() {
echo "Usage: $0 [OPTIONS]"
echo ""
echo "Options:"
echo " --help, -h Show this help message"
echo " --nginx Install with nginx + SSL (default, recommended)"
echo " --simple Simple mode: IP-only on port 5000 (no SSL, for testing)"
echo " --uninstall Remove Aeterna installation"
echo " --backup Create backup of current installation"
echo " --update Update existing installation"
echo " --status Check status of Aeterna services"
echo " --version, -v Show version"
echo ""
echo "Examples:"
echo " $0 Run installation wizard"
echo " $0 --nginx Install with nginx + automatic SSL (recommended)"
echo " $0 --simple Install on port 5000 without SSL (testing/dev)"
echo ""
}
# Detect OS type
detect_os() {
if [ -f /etc/os-release ]; then
. /etc/os-release
OS_ID="${ID}"
OS_ID_LIKE="${ID_LIKE:-}"
elif [ -f /etc/redhat-release ]; then
OS_ID="rhel"
OS_ID_LIKE="rhel fedora"
elif [ -f /etc/debian_version ]; then
OS_ID="debian"
OS_ID_LIKE="debian"
else
OS_ID="unknown"
OS_ID_LIKE=""
fi
}
# Check if system is apt-based (Debian/Ubuntu)
is_apt_based() {
[[ "$OS_ID" == "debian" || "$OS_ID" == "ubuntu" || "$OS_ID_LIKE" == *"debian"* ]]
}
# Check if system is dnf-based (Fedora)
is_dnf_based() {
[[ "$OS_ID" == "fedora" || ("$OS_ID_LIKE" == *"fedora"* && -x "$(command -v dnf)") ]]
}
# Check if system is yum-based (RHEL/CentOS)
is_yum_based() {
[[ "$OS_ID" == "rhel" || "$OS_ID" == "centos" || "$OS_ID" == "rocky" || "$OS_ID" == "almalinux" || "$OS_ID_LIKE" == *"rhel"* ]]
}
# Install system packages based on detected package manager
install_packages() {
local packages=("$@")
detect_os
if is_apt_based; then
sudo apt-get update -qq && sudo apt-get install -y -qq "${packages[@]}"
elif is_dnf_based; then
sudo dnf install -y -q "${packages[@]}"
elif is_yum_based; then
sudo yum install -y -q "${packages[@]}"
else
return 1
fi
}
# Install Docker Compose v2 (cross-platform)
install_docker_compose() {
detect_os
local installed=false
# Try package manager first
if is_apt_based || is_dnf_based || is_yum_based; then
if install_packages docker-compose-plugin; then
installed=true
fi
fi
# Fallback: Download binary directly from GitHub
if [ "$installed" = false ]; then
warning "Package manager installation failed, downloading binary..."
local arch=$(uname -m)
case "$arch" in
x86_64) arch="x86_64" ;;
aarch64|arm64) arch="aarch64" ;;
armv7l) arch="armv7" ;;
*) error "Unsupported architecture: $arch" ;;
esac
local compose_version=$(curl -s https://api.github.com/repos/docker/compose/releases/latest | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
if [ -z "$compose_version" ]; then
compose_version="v2.24.5" # Fallback version
fi
info "Downloading Docker Compose ${compose_version} for ${arch}..."
# Create Docker CLI plugins directory
local plugin_dir="/usr/local/lib/docker/cli-plugins"
sudo mkdir -p "$plugin_dir"
# Download and install
if sudo curl -SL "https://github.com/docker/compose/releases/download/${compose_version}/docker-compose-linux-${arch}" -o "${plugin_dir}/docker-compose"; then
sudo chmod +x "${plugin_dir}/docker-compose"
installed=true
fi
# Also try user-level plugin directory if system-level failed
if [ "$installed" = false ]; then
plugin_dir="${HOME}/.docker/cli-plugins"
mkdir -p "$plugin_dir"
if curl -SL "https://github.com/docker/compose/releases/download/${compose_version}/docker-compose-linux-${arch}" -o "${plugin_dir}/docker-compose"; then
chmod +x "${plugin_dir}/docker-compose"
installed=true
fi
fi
fi
return $([ "$installed" = true ] && echo 0 || echo 1)
}
# Check if command exists
check_command() {
if ! command -v "$1" &> /dev/null; then
return 1
fi
return 0
}
# Get server's public IPv4 address
get_server_ip() {
curl -4 -s --connect-timeout 5 ifconfig.me 2>/dev/null || \
curl -4 -s --connect-timeout 5 icanhazip.com 2>/dev/null || \
curl -4 -s --connect-timeout 5 ipecho.net/plain 2>/dev/null || \
echo "unknown"
}
# Check if port is in use
check_port() {
local port=$1
if command -v ss &> /dev/null; then
ss -tuln | grep -q ":$port " && return 0
elif command -v netstat &> /dev/null; then
netstat -tuln | grep -q ":$port " && return 0
elif command -v lsof &> /dev/null; then
lsof -i:$port &>/dev/null && return 0
fi
return 1
}
# Find a free port starting from a given port
find_free_port() {
local port=$1
while check_port "$port"; do
port=$((port + 1))
done
echo "$port"
}
# Check system requirements
check_requirements() {
echo ""
echo -e "${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${BOLD} System Requirements Check${NC}"
echo -e "${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
local requirements_met=true
export DEBIAN_FRONTEND=noninteractive
# Check curl
if ! check_command curl; then
warning "curl not found. Installing..."
if ! install_packages curl; then
error "Failed to install curl"
fi
success "curl installed"
else
success "curl found"
fi
# Check openssl
if ! check_command openssl; then
warning "openssl not found. Installing..."
if ! install_packages openssl; then
error "Failed to install openssl"
fi
success "openssl installed"
else
success "openssl found"
fi
# Verify openssl can generate random data
if ! openssl rand -base64 16 > /dev/null 2>&1; then
error "openssl is installed but cannot generate random data. Check your system's entropy source."
fi
# Check Docker
if ! check_command docker; then
warning "Docker not found. Installing..."
curl -fsSL https://get.docker.com | sh
sudo usermod -aG docker "$USER"
success "Docker installed"
warning "You may need to log out and back in for Docker group changes to take effect"
else
success "Docker found: $(docker --version | cut -d' ' -f3 | tr -d ',')"
fi
# Check Docker Compose
if ! docker compose version &> /dev/null; then
warning "Docker Compose v2 not found. Installing..."
install_docker_compose
if docker compose version &> /dev/null; then
success "Docker Compose installed: $(docker compose version --short)"
else
error "Failed to install Docker Compose. Please install it manually."
fi
else
success "Docker Compose found: $(docker compose version --short)"
fi
# Check Git
if ! check_command git; then
warning "Git not found. Installing..."
if ! install_packages git; then
error "Failed to install git"
fi
success "Git installed"
else
success "Git found"
fi
# Install nginx and certbot for nginx mode
if [ "$PROXY_MODE" = "nginx" ]; then
if ! check_command nginx; then
warning "nginx not found. Installing..."
if ! install_packages nginx; then
error "Failed to install nginx"
fi
sudo systemctl enable nginx
sudo systemctl start nginx
success "nginx installed and started"
else
success "nginx found"
fi
if ! check_command certbot; then
warning "certbot not found. Installing..."
if ! install_packages certbot python3-certbot-nginx; then
error "Failed to install certbot"
fi
success "certbot installed"
else
success "certbot found"
fi
fi
# Check available ports based on mode
echo ""
info "Checking port availability..."
case "$PROXY_MODE" in
nginx)
BACKEND_PORT=$(find_free_port 8080)
success "Port $BACKEND_PORT is available (backend)"
FRONTEND_PORT=$(find_free_port $((BACKEND_PORT + 1)))
success "Port $FRONTEND_PORT is available (frontend)"
;;
simple)
if check_port 5000; then
warning "Port 5000 is already in use!"
requirements_met=false
else
success "Port 5000 is available"
fi
;;
esac
# Check available disk space (minimum 2GB)
local available_space=$(df -BG / | awk 'NR==2 {print $4}' | tr -d 'G')
if [ "$available_space" -lt 2 ]; then
warning "Low disk space: ${available_space}GB available (minimum 2GB recommended)"
requirements_met=false
else
success "Disk space: ${available_space}GB available"
fi
# Check available memory (minimum 512MB)
local available_mem=$(free -m | awk 'NR==2 {print $7}')
if [ "$available_mem" -lt 512 ]; then
warning "Low memory: ${available_mem}MB available (minimum 512MB recommended)"
else
success "Memory: ${available_mem}MB available"
fi
if [ "$requirements_met" = false ]; then
echo ""
read -p "Some requirements are not met. Continue anyway? [y/N]: " continue_choice
if [ "$continue_choice" != "y" ] && [ "$continue_choice" != "Y" ]; then
error "Installation cancelled due to unmet requirements."
fi
fi
}
# Get user input with default value
prompt() {
local var_name=$1
local prompt_text=$2
local default_value=$3
local is_secret=${4:-""} # Optional parameter, default to empty string
local value=""
if [ "$is_secret" = "true" ]; then
read -sp "$prompt_text [$default_value]: " value
echo ""
else
read -p "$prompt_text [$default_value]: " value
fi
if [ -z "$value" ]; then
value="$default_value"
fi
printf -v "$var_name" '%s' "$value"
}
# Prompt yes/no question
prompt_yn() {
local prompt_text=$1
local default=$2
local result
if [ "$default" = "y" ]; then
read -p "$prompt_text [Y/n]: " result
if [ -z "$result" ] || [ "$result" = "y" ] || [ "$result" = "Y" ]; then
return 0
fi
else
read -p "$prompt_text [y/N]: " result
if [ "$result" = "y" ] || [ "$result" = "Y" ]; then
return 0
fi
fi
return 1
}
# Generate random password
generate_password() {
openssl rand -base64 32 | tr -dc 'a-zA-Z0-9' | head -c 24
}
# Check DNS configuration
check_dns() {
local domain=$1
local server_ip=$(get_server_ip)
info "Checking DNS configuration for $domain..."
if ! check_command dig; then
warning "dig not installed, skipping DNS check"
return
fi
# Resolve domain A record (IPv4 only)
local domain_ip
domain_ip=$(dig +short A "$domain" 2>/dev/null | head -n1)
if [ -z "$domain_ip" ]; then
warning "Could not resolve $domain (no A record found)"
echo -e " ${DIM}Make sure DNS A record points to this server: $server_ip${NC}"
if [ "$PROXY_MODE" != "simple" ]; then
if ! prompt_yn "Continue without DNS? (SSL will fail until DNS is configured)" "n"; then
error "Installation cancelled. Configure DNS first: $domain → $server_ip"
fi
fi
elif [ "$server_ip" = "$domain_ip" ]; then
success "DNS correctly configured ($domain → $server_ip)"
else
echo ""
warning "DNS mismatch detected!"
echo -e " ${DIM}Server IPv4: $server_ip${NC}"
echo -e " ${DIM}Domain A record: $domain_ip${NC}"
echo ""
warning "SSL certificate will fail until DNS points to this server."
warning "Update your DNS A record: $domain → $server_ip"
if [ "$PROXY_MODE" != "simple" ]; then
if ! prompt_yn "Continue anyway? (SSL will fail until DNS is fixed)" "n"; then
error "Installation cancelled. Fix DNS first: $domain → $server_ip"
fi
fi
fi
}
# Check firewall status
check_firewall() {
echo ""
info "Checking firewall configuration..."
if check_command ufw; then
if sudo ufw status | grep -q "Status: active"; then
case "$PROXY_MODE" in
nginx)
success "nginx mode: No additional firewall configuration needed"
;;
simple)
local port_allowed=$(sudo ufw status | grep -E "5000/tcp|5000 " | grep -c "ALLOW" || echo "0")
if [ "$port_allowed" -eq 0 ]; then
warning "UFW firewall is active but port 5000 may not be open"
if prompt_yn "Open port 5000 in firewall?" "y"; then
sudo ufw allow 5000/tcp
success "Firewall port 5000 opened"
fi
else
success "Firewall configured correctly (port 5000 open)"
fi
;;
esac
else
success "UFW firewall is inactive"
fi
elif check_command firewall-cmd; then
if sudo firewall-cmd --state 2>/dev/null | grep -q "running"; then
warning "firewalld is active. Ensure required ports are open."
fi
else
success "No firewall detected"
fi
}
# Select proxy mode
select_proxy_mode() {
echo ""
echo -e "${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${BOLD} Installation Mode${NC}"
echo -e "${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
echo -e " ${CYAN}1)${NC} ${BOLD}nginx + SSL${NC} (recommended)"
echo -e " ${DIM}• Automatic nginx + certbot SSL setup${NC}"
echo -e " ${DIM}• Requires a domain name${NC}"
echo -e " ${DIM}• Dynamically assigns internal ports${NC}"
echo ""
echo -e " ${CYAN}2)${NC} ${BOLD}Simple${NC} - IP only, no SSL (testing/dev)"
echo -e " ${DIM}• No domain required, access via IP${NC}"
echo -e " ${DIM}• No SSL/HTTPS (not for production!)${NC}"
echo -e " ${DIM}• Runs on port 5000${NC}"
echo ""
read -p "Select installation mode [1]: " mode_choice
mode_choice=${mode_choice:-1}
case $mode_choice in
1)
PROXY_MODE="nginx"
success "Using nginx mode (with SSL)"
;;
2)
PROXY_MODE="simple"
success "Using Simple mode (IP only, port 5000)"
warning "This mode has no SSL - not recommended for production!"
;;
*)
PROXY_MODE="nginx"
success "Using nginx mode (with SSL)"
;;
esac
}
# Collect configuration
collect_config() {
echo ""
echo -e "${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${BOLD} Configuration${NC}"
echo -e "${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
local server_ip=$(get_server_ip)
# Domain/IP Configuration
echo ""
if [ "$PROXY_MODE" = "simple" ]; then
echo -e "${CYAN}📌 Access Configuration${NC}"
echo -e "${DIM}Your server IP: ${BOLD}$server_ip${NC}"
echo ""
DOMAIN="$server_ip"
ACME_EMAIL=""
ALLOWED_ORIGINS="http://$server_ip:5000"
success "Will be accessible at: http://$server_ip:5000"
else
echo -e "${CYAN}📌 Domain Configuration${NC}"
echo -e "${DIM}Your domain must point to this server's IP address${NC}"
echo ""
prompt DOMAIN "Enter your domain (e.g., aeterna.example.com)" ""
if [ -z "$DOMAIN" ]; then
error "Domain is required!"
fi
# Check DNS
check_dns "$DOMAIN"
ALLOWED_ORIGINS="https://$DOMAIN"
ACME_EMAIL="admin@$DOMAIN"
fi
# Database Configuration
echo ""
echo -e "${CYAN}🗄️ Database Configuration${NC}"
echo -e "${DIM}SQLite database will be created automatically${NC}"
echo -e "${DIM}Database file location: ${INSTALL_DIR:-/opt/aeterna}/data/aeterna.db${NC}"
echo ""
# Installation Directory
echo ""
echo -e "${CYAN}📁 Installation Directory${NC}"
prompt INSTALL_DIR "Installation directory" "/opt/aeterna"
# Check firewall
check_firewall
}
# Show configuration summary and confirm
confirm_installation() {
local server_ip=$(get_server_ip)
echo ""
echo -e "${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${BOLD} Configuration Summary${NC}"
echo -e "${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
# Mode display
case "$PROXY_MODE" in
nginx)
echo -e " ${CYAN}Mode:${NC} ${BOLD}nginx + SSL${NC}"
echo -e " ${CYAN}Access URL:${NC} https://$DOMAIN"
;;
simple)
echo -e " ${CYAN}Mode:${NC} ${BOLD}Simple${NC} (IP only, no SSL)"
echo -e " ${CYAN}Access URL:${NC} http://$server_ip:5000"
echo -e " ${YELLOW}⚠ Warning:${NC} No SSL - not for production use!"
;;
esac
echo ""
echo -e " ${CYAN}Database:${NC} SQLite (file: $INSTALL_DIR/data/aeterna.db)"
echo ""
echo ""
echo ""
echo -e " ${CYAN}Install Dir:${NC} $INSTALL_DIR"
echo ""
echo -e "${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
# Validate critical inputs before proceeding
if [ -z "${DOMAIN:-}" ]; then
error "DOMAIN is not set"
fi
# SQLite mode uses file-based database and doesn't need credentials
if [ -z "${INSTALL_DIR:-}" ]; then
error "INSTALL_DIR is not set"
fi
# Validate domain format (basic check)
if ! echo "$DOMAIN" | grep -qE '^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$'; then
warning "Domain format may be invalid: $DOMAIN"
if ! prompt_yn "Continue anyway?" "n"; then
error "Installation cancelled"
fi
fi
if ! prompt_yn "Proceed with installation?" "y"; then
error "Installation cancelled by user."
fi
}
# Clone or update repository
setup_repository() {
echo ""
step "Setting up Aeterna repository..."
if [ -d "$INSTALL_DIR" ]; then
warning "Directory $INSTALL_DIR already exists."
if prompt_yn "Update existing installation?" "n"; then
cd "$INSTALL_DIR"
git fetch origin
git pull origin "$BRANCH"
success "Repository updated"
else
error "Installation cancelled. Remove existing directory first: rm -rf $INSTALL_DIR"
fi
else
sudo mkdir -p "$INSTALL_DIR"
sudo chown "$USER":"$USER" "$INSTALL_DIR"
git clone -b "$BRANCH" https://github.com/alpyxn/aeterna.git "$INSTALL_DIR"
success "Repository cloned"
fi
cd "$INSTALL_DIR"
}
# Get compose file for current mode
get_compose_file() {
case "$PROXY_MODE" in
nginx) echo "docker-compose.proxy.yml" ;;
simple) echo "docker-compose.simple.yml" ;;
*) echo "docker-compose.proxy.yml" ;;
esac
}
# Validate encryption key format
validate_encryption_key() {
local key_file="$1"
if [ ! -f "$key_file" ]; then
return 1
fi
local key_content
key_content=$(cat "$key_file" | tr -d '[:space:]')
# Check key is not empty
if [ -z "$key_content" ]; then
return 1
fi
# Validate base64 format and length (should decode to exactly 32 bytes)
local decoded_length
decoded_length=$(echo "$key_content" | base64 -d 2>/dev/null | wc -c)
if [ "$decoded_length" -ne 32 ]; then
return 1
fi
return 0
}
# Generate encryption key with validation
generate_encryption_key() {
local key_file="$1"
local max_attempts=5
local attempt=0
while [ $attempt -lt $max_attempts ]; do
attempt=$((attempt + 1))
# Generate key
if ! ENCRYPTION_KEY=$(openssl rand -base64 32 2>/dev/null); then
error "Failed to generate encryption key: openssl command failed"
fi
# Remove whitespace
ENCRYPTION_KEY=$(echo "$ENCRYPTION_KEY" | tr -d '[:space:]')
# Validate key format
if ! echo "$ENCRYPTION_KEY" | base64 -d > /dev/null 2>&1; then
warning "Generated invalid base64 key, retrying... (attempt $attempt/$max_attempts)"
continue
fi
local decoded_length
decoded_length=$(echo "$ENCRYPTION_KEY" | base64 -d | wc -c)
if [ "$decoded_length" -ne 32 ]; then
warning "Generated key has wrong length ($decoded_length bytes), retrying... (attempt $attempt/$max_attempts)"
continue
fi
# Write key file atomically (write to temp, then move)
local temp_file="${key_file}.tmp"
if ! echo "$ENCRYPTION_KEY" > "$temp_file" 2>/dev/null; then
error "Failed to write encryption key to temporary file: $temp_file"
fi
# Set secure permissions before moving
if ! chmod 600 "$temp_file" 2>/dev/null; then
rm -f "$temp_file"
error "Failed to set permissions on encryption key file"
fi
# Atomic move
if ! mv "$temp_file" "$key_file" 2>/dev/null; then
rm -f "$temp_file"
error "Failed to create encryption key file: $key_file"
fi
# Verify file was created and has correct permissions
if [ ! -f "$key_file" ]; then
error "Encryption key file was not created: $key_file"
fi
local file_perms
file_perms=$(stat -c "%a" "$key_file" 2>/dev/null || stat -f "%OLp" "$key_file" 2>/dev/null || echo "unknown")
if [ "$file_perms" != "600" ] && [ "$file_perms" != "0600" ]; then
warning "Encryption key file has incorrect permissions ($file_perms), fixing..."
chmod 600 "$key_file" || error "Failed to fix encryption key file permissions"
fi
# Final validation
if ! validate_encryption_key "$key_file"; then
warning "Generated key failed validation, retrying... (attempt $attempt/$max_attempts)"
rm -f "$key_file"
continue
fi
return 0
done
error "Failed to generate valid encryption key after $max_attempts attempts"
}
# Create environment file
create_env_file() {
step "Creating environment configuration..."
# Validate INSTALL_DIR is set and valid
if [ -z "${INSTALL_DIR:-}" ]; then
error "INSTALL_DIR is not set"
fi
if [ ! -d "$INSTALL_DIR" ]; then
error "Installation directory does not exist: $INSTALL_DIR"
fi
# Create data directory for SQLite database
step "Creating data directory for SQLite database..."
if ! mkdir -p "$INSTALL_DIR/data" 2>/dev/null; then
error "Failed to create data directory: $INSTALL_DIR/data"
fi
# Verify directory was created
if [ ! -d "$INSTALL_DIR/data" ]; then
error "Data directory was not created: $INSTALL_DIR/data"
fi
# Generate encryption key file BEFORE creating .env (security: key never goes in .env)
step "Generating encryption key..."
# Create secrets directory with error handling
if ! mkdir -p "$INSTALL_DIR/secrets" 2>/dev/null; then
error "Failed to create secrets directory: $INSTALL_DIR/secrets"
fi
# Verify directory was created
if [ ! -d "$INSTALL_DIR/secrets" ]; then
error "Secrets directory was not created: $INSTALL_DIR/secrets"
fi
local key_file="$INSTALL_DIR/secrets/encryption_key"
if [ -f "$key_file" ]; then
info "Encryption key file already exists, validating..."
if validate_encryption_key "$key_file"; then
info "Existing encryption key is valid, preserving it"
info "To regenerate, delete: $key_file"
else
warning "Existing encryption key file is invalid or corrupted"
if prompt_yn "Regenerate encryption key? (WARNING: This will make existing encrypted data unreadable)" "n"; then
rm -f "$key_file"
generate_encryption_key "$key_file"
success "Encryption key regenerated"
else
error "Cannot proceed with invalid encryption key. Please fix or remove: $key_file"
fi
fi
else
generate_encryption_key "$key_file"
success "Encryption key generated and stored securely in secrets/encryption_key"
fi
# Final verification
if ! validate_encryption_key "$key_file"; then
error "Encryption key validation failed after generation"
fi
# Create .env file atomically
local env_temp=".env.tmp"
cat > "$env_temp" << EOF
# Aeterna Production Configuration
# Generated by install.sh v${VERSION} on $(date)
# Mode: $PROXY_MODE
# Domain Configuration
DOMAIN=$DOMAIN
ACME_EMAIL=${ACME_EMAIL:-}
# Database Configuration
# SQLite database will be created automatically at ./data/aeterna.db
# No database credentials needed for SQLite
# Application Settings
ENV=production
ALLOWED_ORIGINS=$ALLOWED_ORIGINS
VITE_API_URL=/api
# Security Note:
# Encryption key is stored in secrets/encryption_key (NOT in this file)
# The key file is mounted as a Docker secret at /run/secrets/encryption_key
# Installation Mode
PROXY_MODE=$PROXY_MODE
# Internal Ports
BACKEND_PORT=${BACKEND_PORT:-8080}
FRONTEND_PORT=${FRONTEND_PORT:-8081}
EOF
# Set permissions before moving
if ! chmod 600 "$env_temp" 2>/dev/null; then
rm -f "$env_temp"
error "Failed to set permissions on .env file"
fi
# Atomic move
if ! mv "$env_temp" .env 2>/dev/null; then
rm -f "$env_temp"
error "Failed to create .env file"
fi
# Verify .env was created
if [ ! -f .env ]; then
error ".env file was not created"
fi
success "Environment file created"
}
# Setup nginx with SSL certificate
setup_nginx() {
local nginx_available="/etc/nginx/sites-available/aeterna"
local nginx_enabled="/etc/nginx/sites-enabled/aeterna"
step "Configuring nginx..."
# Step 1: Create initial HTTP-only config (needed for certbot to verify domain)
sudo tee "$nginx_available" > /dev/null << EOF
server {
listen 80;
server_name $DOMAIN;
client_max_body_size 12m;
# API Backend
location /api {
proxy_pass http://127.0.0.1:${BACKEND_PORT:-8080};
proxy_http_version 1.1;
proxy_set_header Upgrade \$http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
proxy_cache_bypass \$http_upgrade;
}
# Frontend
location / {
proxy_pass http://127.0.0.1:${FRONTEND_PORT:-8081};
proxy_http_version 1.1;
proxy_set_header Upgrade \$http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
proxy_cache_bypass \$http_upgrade;
}
}
EOF
# Step 2: Enable site and remove default if it conflicts
if [ ! -L "$nginx_enabled" ]; then
sudo ln -sf "$nginx_available" "$nginx_enabled"
fi
# Remove default site if it exists (it listens on port 80 and conflicts)
if [ -L "/etc/nginx/sites-enabled/default" ]; then
sudo rm -f /etc/nginx/sites-enabled/default
info "Removed default nginx site to avoid port 80 conflict"
fi
# Step 3: Test and reload nginx with HTTP config
if ! sudo nginx -t 2>/dev/null; then
error "nginx configuration test failed. Check: sudo nginx -t"
fi
sudo systemctl reload nginx
success "nginx configured with HTTP"
# Step 4: Obtain SSL certificate
step "Obtaining SSL certificate for $DOMAIN..."
local certbot_email="${ACME_EMAIL:-admin@$DOMAIN}"
if sudo certbot --nginx -d "$DOMAIN" --non-interactive --agree-tos -m "$certbot_email" --redirect; then
success "SSL certificate obtained and nginx configured with HTTPS"
else
warning "Failed to obtain SSL certificate automatically"
warning "This usually means DNS is not pointing to this server yet"
echo ""
info "You can obtain the certificate later by running:"
echo " sudo certbot --nginx -d $DOMAIN"
echo ""
info "Aeterna is accessible via HTTP in the meantime: http://$DOMAIN"
fi