-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebctl.sh
More file actions
executable file
·3458 lines (3017 loc) · 124 KB
/
webctl.sh
File metadata and controls
executable file
·3458 lines (3017 loc) · 124 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
# ============================================================
# WEB SETUP SCRIPT v2.1
# Manages: Static, WordPress, PHP, Reverse Proxy sites
# Stores sites in: /home/$SUDO_USER/sites/
# ============================================================
set -o pipefail
# ── Colors & Styles ──────────────────────────────────────────
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
MAGENTA='\033[0;35m'
WHITE='\033[1;37m'
BOLD='\033[1m'
DIM='\033[2m'
UNDERLINE='\033[4m'
NC='\033[0m'
# Symbols
ARROW=">" BULLET="*" CHECK="[ok]" CROSS="[!!]" WARN="[!]"
# ── Config ───────────────────────────────────────────────────
VERSION="2.1"
SCRIPT_NAME="$(basename "$0")"
REAL_USER="${SUDO_USER:-$USER}"
SITES_ROOT="/home/${REAL_USER}/sites"
BACKUP_ROOT="/home/${REAL_USER}/backups"
BACKUP_RETENTION=7
BACKUP_REMOTE_CONF="${SITES_ROOT}/.backup-remote.conf"
LOG_FILE="/var/log/websetup.log"
LOCK_FILE="/run/websetup.lock"
# ── Distro Detection ────────────────────────────────────────
DISTRO_FAMILY="unknown"
WEB_USER="www-data"
NOLOGIN_SHELL="/usr/sbin/nologin"
PHP_FPM_SERVICE=""
PHP_POOL_DIR=""
NGINX_SITES="/etc/nginx/sites-available"
NGINX_ENABLED="/etc/nginx/sites-enabled"
if [[ -f /etc/os-release ]]; then
# shellcheck disable=SC1091
source /etc/os-release
case "$ID" in
arch|manjaro|endeavouros|artix|garuda)
DISTRO_FAMILY="arch"
WEB_USER="http"
NOLOGIN_SHELL="/usr/bin/nologin"
;;
debian|ubuntu|linuxmint|pop)
DISTRO_FAMILY="debian"
WEB_USER="www-data"
NOLOGIN_SHELL="/usr/sbin/nologin"
;;
esac
fi
# Auto-detect latest installed PHP version
if [[ "$DISTRO_FAMILY" == "arch" ]]; then
# Arch uses unversioned PHP paths
PHP_VERSION=$(php -r 'echo PHP_MAJOR_VERSION.".".PHP_MINOR_VERSION;' 2>/dev/null || echo "")
PHP_FPM_SERVICE="php-fpm"
PHP_POOL_DIR="/etc/php/php-fpm.d"
else
# Debian uses versioned PHP directories
PHP_VERSION=$(find /etc/php -maxdepth 1 -mindepth 1 -type d 2>/dev/null \
| grep -oP '\d+\.\d+' | sort -V | tail -1 || true)
PHP_VERSION="${PHP_VERSION:-8.2}"
PHP_FPM_SERVICE="php${PHP_VERSION}-fpm"
PHP_POOL_DIR="/etc/php/${PHP_VERSION}/fpm/pool.d"
fi
# ── Helpers ──────────────────────────────────────────────────
log() {
local timestamp
timestamp="$(date '+%H:%M:%S')"
echo -e " ${GREEN}${CHECK}${NC} ${DIM}${timestamp}${NC} $1" | tee -a "$LOG_FILE"
}
warn() {
local timestamp
timestamp="$(date '+%H:%M:%S')"
echo -e " ${YELLOW}${WARN}${NC} ${DIM}${timestamp}${NC} ${YELLOW}$1${NC}" | tee -a "$LOG_FILE"
}
error() {
local timestamp
timestamp="$(date '+%H:%M:%S')"
echo -e " ${RED}${CROSS}${NC} ${DIM}${timestamp}${NC} ${RED}${BOLD}$1${NC}" | tee -a "$LOG_FILE"
exit 1 # EXIT trap handles lock cleanup
}
info() {
echo -e " ${CYAN}${ARROW}${NC} $1"
}
# Section header
header() {
local text="$1"
echo
echo -e " ${BOLD}${BLUE}=== ${WHITE}${text} ${BLUE}===${NC}"
echo
}
# Separator line
separator() {
echo -e " ${DIM}$(printf '%50s' '' | tr ' ' '-')${NC}"
}
# Confirmation prompt
confirm() {
echo -ne " ${YELLOW}?${NC} $1 ${DIM}[y/N]${NC} "
read -r ans
[[ "$ans" =~ ^[Yy]$ ]]
}
# Spinner for long operations
spinner() {
local pid=$1
local msg="${2:-Working...}"
local frames=("⠋" "⠙" "⠹" "⠸" "⠼" "⠴" "⠦" "⠧" "⠇" "⠏")
local i=0
while kill -0 "$pid" 2>/dev/null; do
echo -ne "\r ${MAGENTA}${frames[$i]}${NC} ${msg}"
i=$(( (i + 1) % ${#frames[@]} ))
sleep 0.1
done
wait "$pid"
local exit_code=$?
echo -ne "\r$(printf '%*s' 60 '')\r"
return $exit_code
}
# ── Input Validation ─────────────────────────────────────────
validate_domain() {
local domain="$1"
if [[ -z "$domain" ]]; then
error "Domain name cannot be empty."
fi
# Allow local TLDs (.local, .test, .localhost, .dev) and standard domains
if ! [[ "$domain" =~ ^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$ ]]; then
error "Invalid domain format: ${domain}. Expected something like example.com or myapp.local"
fi
}
# Check if domain uses a local TLD
is_local_domain() {
local domain="$1"
[[ "$domain" =~ \.(local|test|localhost|internal)$ ]]
}
validate_port() {
local port="$1"
if [[ -z "$port" ]]; then
error "Port number cannot be empty."
fi
if ! [[ "$port" =~ ^[0-9]+$ ]]; then
error "Port must be a number, got: ${port}"
fi
if (( port < 1 || port > 65535 )); then
error "Port must be between 1 and 65535, got: ${port}"
fi
if (( port < 1024 )); then
warn "Port ${port} is a privileged port (< 1024). Make sure your app runs as root or has the right capabilities."
fi
}
validate_email() {
local email="$1"
if [[ -z "$email" ]]; then
error "Email address cannot be empty."
fi
if ! [[ "$email" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
error "Invalid email format: ${email}"
fi
}
validate_username() {
local username="$1"
if [[ -z "$username" ]]; then
error "Username cannot be empty."
fi
if ! [[ "$username" =~ ^[a-z_][a-z0-9_-]{0,31}$ ]]; then
error "Invalid username: ${username}. Use lowercase letters, numbers, hyphens, underscores. Must start with a letter or underscore."
fi
}
# ── /etc/hosts Management ────────────────────────────────────
add_to_hosts() {
local domain="$1"
local hosts_line="127.0.0.1 ${domain}"
if grep -qF "127.0.0.1 ${domain}" /etc/hosts 2>/dev/null; then
log "${domain} already in /etc/hosts"
return
fi
# Add under a managed comment block
if ! grep -q "# -- websetup managed --" /etc/hosts; then
echo -e "\n# -- websetup managed --" >> /etc/hosts
fi
sed -i "/# -- websetup managed --/a ${hosts_line}" /etc/hosts
log "Added ${domain} to /etc/hosts -> 127.0.0.1"
# Fix nsswitch.conf if using a .local domain (mDNS conflict)
if [[ "$domain" == *.local ]]; then
fix_nsswitch_local
fi
}
fix_nsswitch_local() {
local nsswitch="/etc/nsswitch.conf"
[[ -f "$nsswitch" ]] || return 0
local hosts_line
hosts_line=$(grep "^hosts:" "$nsswitch" 2>/dev/null) || return 0
# Check if mdns_minimal comes before files -- .local domains won't resolve from /etc/hosts
if echo "$hosts_line" | grep -qP 'mdns_minimal.*\[NOTFOUND=return\].*files'; then
warn ".local domains won't resolve: mdns_minimal blocks /etc/hosts lookups"
info "Fixing /etc/nsswitch.conf (moving 'files' before 'mdns_minimal')..."
sed -i 's/^\(hosts:.*\)mdns_minimal \[NOTFOUND=return\] \(.*\)files \(.*\)/\1files mdns_minimal [NOTFOUND=return] \2\3/' "$nsswitch"
if grep "^hosts:" "$nsswitch" | grep -qP 'files.*mdns_minimal'; then
log "Fixed nsswitch.conf: /etc/hosts now checked before mDNS"
else
warn "Could not auto-fix nsswitch.conf. Manually move 'files' before 'mdns_minimal' in ${nsswitch}"
fi
fi
}
remove_from_hosts() {
local domain="$1"
local escaped="${domain//./\\.}"
if grep -q "127\.0\.0\.1.*${escaped}" /etc/hosts 2>/dev/null; then
sed -i "/^127\.0\.0\.1[[:space:]]\+${escaped}$/d" /etc/hosts
log "Removed ${domain} from /etc/hosts"
fi
}
# ── Lock File ────────────────────────────────────────────────
acquire_lock() {
if [[ -f "$LOCK_FILE" ]]; then
local lock_pid
lock_pid=$(cat "$LOCK_FILE" 2>/dev/null)
if kill -0 "$lock_pid" 2>/dev/null; then
error "Another instance is running (PID: ${lock_pid}). If this is wrong, remove ${LOCK_FILE}"
else
warn "Stale lock file found (PID ${lock_pid} not running). Removing."
rm -f "$LOCK_FILE"
fi
fi
echo $$ > "$LOCK_FILE"
}
cleanup_lock() {
rm -f "$LOCK_FILE" 2>/dev/null || true
}
# ── Trap Handlers ────────────────────────────────────────────
cleanup() {
local exit_code=$?
cleanup_lock
if [[ $exit_code -ne 0 ]] && [[ $exit_code -ne 130 ]]; then
echo
warn "Script exited with code ${exit_code}. Check log: ${LOG_FILE}"
fi
exit $exit_code
}
trap cleanup EXIT
trap 'echo; warn "Interrupted by user."; exit 130' INT TERM
# ── Pre-flight Checks ───────────────────────────────────────
check_root() {
if [[ $EUID -ne 0 ]]; then
echo -e "\n ${RED}${CROSS} This script must be run as root.${NC}"
echo -e " ${DIM}Usage: sudo ${SCRIPT_NAME}${NC}\n"
exit 1
fi
if [[ -z "$REAL_USER" ]] || [[ "$REAL_USER" == "root" ]]; then
echo -e "\n ${RED}${CROSS} Cannot determine the real user.${NC}"
echo -e " ${DIM}Run with: sudo ${SCRIPT_NAME} (not as direct root login)${NC}\n"
exit 1
fi
}
check_os() {
if [[ ! -f /etc/os-release ]]; then
warn "Cannot detect OS. This script supports Debian/Ubuntu and Arch-based systems."
confirm "Continue anyway?" || exit 0
elif [[ "$DISTRO_FAMILY" == "unknown" ]]; then
# shellcheck disable=SC1091
source /etc/os-release
warn "Detected OS: ${PRETTY_NAME}. This script supports Debian/Ubuntu and Arch-based systems."
confirm "Continue anyway?" || exit 0
else
# shellcheck disable=SC1091
source /etc/os-release
log "Detected OS: ${PRETTY_NAME} (${DISTRO_FAMILY})"
fi
}
# ── Nginx sites-available/sites-enabled setup ───────────────
setup_nginx_dirs() {
# Arch doesn't ship with sites-available/sites-enabled by default
if [[ ! -d "$NGINX_SITES" ]]; then
mkdir -p "$NGINX_SITES"
log "Created ${NGINX_SITES}"
fi
if [[ ! -d "$NGINX_ENABLED" ]]; then
mkdir -p "$NGINX_ENABLED"
log "Created ${NGINX_ENABLED}"
fi
# Ensure nginx.conf includes sites-enabled and doesn't have a conflicting default server
if [[ -f /etc/nginx/nginx.conf ]]; then
# Comment out the default server block that ships with Arch/stock nginx
# This block serves the "Welcome to nginx!" page and conflicts with site configs
if grep -qP '^\s*server\s*\{' /etc/nginx/nginx.conf; then
if grep -A5 'server {' /etc/nginx/nginx.conf | grep -q '/usr/share/nginx/html\|listen.*80'; then
info "Commenting out default server block in nginx.conf..."
# Use awk to comment out the first uncommented server { ... } block
awk '
/^[^#]*server\s*\{/ && !found {
found=1; depth=0
}
found && !done {
if (/\{/) depth++
if (/\}/) depth--
$0 = "#webctl " $0
if (depth == 0) done=1
}
{ print }
' /etc/nginx/nginx.conf > /etc/nginx/nginx.conf.tmp \
&& mv /etc/nginx/nginx.conf.tmp /etc/nginx/nginx.conf
log "Commented out default server block in nginx.conf"
fi
fi
# Add include directive for sites-enabled inside the http block
if ! grep -q "include.*sites-enabled" /etc/nginx/nginx.conf; then
if grep -q "^http {" /etc/nginx/nginx.conf; then
sed -i '/^http {/a\ include /etc/nginx/sites-enabled/*;' /etc/nginx/nginx.conf
log "Added sites-enabled include to nginx.conf"
else
sed -i '/^}/i\ include /etc/nginx/sites-enabled/*;' /etc/nginx/nginx.conf
log "Added sites-enabled include to nginx.conf"
fi
fi
fi
}
# ── Package Manager Abstraction ─────────────────────────────
pkg_update() {
case "$DISTRO_FAMILY" in
debian)
apt update -qq 2>&1 | tee -a "$LOG_FILE"
;;
arch)
pacman -Sy 2>&1 | tee -a "$LOG_FILE"
;;
*)
warn "Unknown package manager. Install dependencies manually."
return 1
;;
esac
}
pkg_install() {
local pkg="$1"
case "$DISTRO_FAMILY" in
debian)
DEBIAN_FRONTEND=noninteractive apt install -y "$pkg" 2>&1 | tee -a "$LOG_FILE"
;;
arch)
pacman -S --noconfirm --needed "$pkg" 2>&1 | tee -a "$LOG_FILE"
;;
*)
warn "Cannot install ${pkg} — unknown package manager."
return 1
;;
esac
}
ask_local_or_public() {
IS_LOCAL=false
echo -e " ${BOLD}${GREEN}1${NC} | ${BOLD}Public${NC} ${DIM}-- real domain with DNS (e.g. example.com)${NC}"
echo -e " ${BOLD}${CYAN}2${NC} | ${BOLD}Local${NC} ${DIM}-- local dev domain via /etc/hosts (e.g. myapp.local)${NC}"
echo
echo -ne " ${CYAN}${ARROW}${NC} Public or local? ${DIM}[1-2]${NC}: "
read -r scope_choice
case "$scope_choice" in
2) IS_LOCAL=true ;;
1) IS_LOCAL=false ;;
*) warn "Defaulting to public." ;;
esac
}
check_dependencies() {
# Build dependency list based on site type AND local/public mode
local base_deps=(nginx curl unzip openssl)
local need_php=false
local need_db=false
local need_ssl=false
# wget is useful but not strictly required for local static/proxy
if [[ "$SITE_TYPE" == "wordpress" ]]; then
base_deps+=(wget) # needed to download WordPress
fi
case "$SITE_TYPE" in
wordpress) need_php=true; need_db=true ;;
php) need_php=true ;;
static|proxy) ;;
esac
# Only require SSL tools for public sites
if ! $IS_LOCAL; then
need_ssl=true
base_deps+=(certbot)
fi
header "Checking Dependencies"
local missing=()
for cmd in "${base_deps[@]}"; do
if command -v "$cmd" &>/dev/null; then
log "${cmd} ${DIM}$(command -v "$cmd")${NC}"
else
missing+=("$cmd")
warn "${cmd} — ${RED}not found${NC}"
fi
done
# Check certbot nginx plugin (only for public sites)
if $need_ssl; then
if command -v certbot &>/dev/null; then
if ! certbot plugins 2>/dev/null | grep -q "nginx"; then
local certbot_nginx_pkg="python3-certbot-nginx"
[[ "$DISTRO_FAMILY" == "arch" ]] && certbot_nginx_pkg="certbot-nginx"
missing+=("$certbot_nginx_pkg")
warn "certbot nginx plugin — ${RED}not found${NC}"
else
log "certbot nginx plugin"
fi
fi
else
info "SSL tools not needed for local site — skipping certbot"
fi
if $need_php; then
if command -v php &>/dev/null; then
log "php ${DIM}$(php -r 'echo PHP_VERSION;')${NC}"
else
missing+=("php")
warn "php — ${RED}not found${NC}"
fi
else
info "PHP not needed for ${SITE_TYPE} — skipping"
fi
if $need_db; then
if command -v mysql &>/dev/null; then
log "mysql/mariadb"
else
missing+=("mysql")
warn "mysql — ${RED}not found${NC}"
fi
else
info "Database not needed for ${SITE_TYPE} — skipping"
fi
if [[ ${#missing[@]} -gt 0 ]]; then
echo
separator
warn "Missing ${#missing[@]} package(s): ${BOLD}${missing[*]}${NC}"
separator
echo
if confirm "Install missing dependencies now?"; then
info "Updating package lists..."
pkg_update &
spinner $! "Updating package lists..."
log "Package lists updated"
local php_installed=false
for pkg in "${missing[@]}"; do
case "$pkg" in
php)
if ! $php_installed; then
if [[ "$DISTRO_FAMILY" == "arch" ]]; then
pkg_install php &
spinner $! "Installing PHP..."
pkg_install php-fpm &
spinner $! "Installing PHP-FPM..."
for ext in php-gd php-intl php-sodium php-imagick imagemagick; do
pkg_install "$ext" &>/dev/null || true
done
local php_ini="/etc/php/php.ini"
if [[ -f "$php_ini" ]]; then
for ext in mysqli curl gd mbstring xml zip intl bcmath sodium imagick; do
sed -i "s/^;extension=${ext}/extension=${ext}/" "$php_ini" 2>/dev/null || true
done
log "PHP extensions enabled in php.ini"
fi
PHP_VERSION=$(php -r 'echo PHP_MAJOR_VERSION.".".PHP_MINOR_VERSION;' 2>/dev/null || echo "")
PHP_FPM_SERVICE="php-fpm"
PHP_POOL_DIR="/etc/php/php-fpm.d"
else
if ! find /etc/php -maxdepth 1 -mindepth 1 -type d &>/dev/null 2>&1; then
PHP_VERSION=$(apt-cache search "^php[0-9]" 2>/dev/null \
| grep -oP 'php\K\d+\.\d+' | sort -V | tail -1)
PHP_VERSION="${PHP_VERSION:-8.2}"
log "Latest available PHP: ${PHP_VERSION}"
fi
apt install -y "php${PHP_VERSION}" "php${PHP_VERSION}-fpm" 2>&1 | tee -a "$LOG_FILE" &
spinner $! "Installing PHP ${PHP_VERSION}..."
apt install -y "php${PHP_VERSION}-"{mysql,curl,gd,mbstring,xml,zip,intl,bcmath,imagick} imagemagick &>/dev/null &
spinner $! "Installing PHP extensions..."
PHP_FPM_SERVICE="php${PHP_VERSION}-fpm"
PHP_POOL_DIR="/etc/php/${PHP_VERSION}/fpm/pool.d"
fi
log "PHP ${PHP_VERSION} + extensions installed"
php_installed=true
fi
;;
mysql)
if [[ "$DISTRO_FAMILY" == "arch" ]]; then
pkg_install mariadb &
spinner $! "Installing MariaDB..."
if [[ ! -d /var/lib/mysql/mysql ]]; then
info "Initializing MariaDB data directory..."
mariadb-install-db --user=mysql --basedir=/usr --datadir=/var/lib/mysql 2>&1 | tee -a "$LOG_FILE"
log "MariaDB data directory initialized"
fi
else
apt install -y mariadb-server 2>&1 | tee -a "$LOG_FILE" &
spinner $! "Installing MariaDB..."
fi
systemctl enable --now mariadb 2>/dev/null || true
log "MariaDB installed and started"
;;
*)
pkg_install "$pkg" &
spinner $! "Installing ${pkg}..."
log "Installed ${pkg}"
;;
esac
done
else
error "Cannot continue without required dependencies."
fi
else
echo
log "${GREEN}All dependencies satisfied${NC}"
fi
}
# ── Banner ───────────────────────────────────────────────────
show_banner() {
echo
echo -e " ${BOLD}${BLUE}=================================================${NC}"
echo -e " ${BOLD}${WHITE} WEB SETUP SCRIPT${NC} ${DIM}v${VERSION}${NC}"
echo -e " ${DIM} Nginx ${BULLET} WordPress ${BULLET} PHP ${BULLET} Reverse Proxy${NC}"
echo -e " ${BOLD}${BLUE}=================================================${NC}"
echo -e " ${DIM}User: ${REAL_USER} | OS: ${DISTRO_FAMILY} | PHP: ${PHP_VERSION} | Sites: ${SITES_ROOT}${NC}"
echo
}
# ── Main Menu ────────────────────────────────────────────────
manage_services() {
header "Service Manager"
# Build list of services to check based on what's installed
local -a services=()
local -a labels=()
# Nginx — always relevant
services+=("nginx")
labels+=("Nginx")
# PHP-FPM — only if PHP is installed
if command -v php &>/dev/null; then
services+=("${PHP_FPM_SERVICE}")
labels+=("PHP-FPM (${PHP_FPM_SERVICE})")
fi
# MariaDB/MySQL — only if installed
if command -v mysql &>/dev/null; then
if systemctl list-unit-files mariadb.service &>/dev/null 2>&1; then
services+=("mariadb")
labels+=("MariaDB")
elif systemctl list-unit-files mysql.service &>/dev/null 2>&1; then
services+=("mysql")
labels+=("MySQL")
fi
fi
# SSH/SSHD — check for SFTP support
if systemctl list-unit-files sshd.service &>/dev/null 2>&1; then
services+=("sshd")
labels+=("SSH (sshd)")
elif systemctl list-unit-files ssh.service &>/dev/null 2>&1; then
services+=("ssh")
labels+=("SSH (ssh)")
fi
# Check each service
local -a stopped=()
local -a stopped_labels=()
local -a not_enabled=()
local -a not_enabled_labels=()
local all_ok=true
for i in "${!services[@]}"; do
local svc="${services[$i]}"
local label="${labels[$i]}"
local status_icon=""
local enabled_icon=""
local status_text=""
# Check if running
if systemctl is-active --quiet "$svc" 2>/dev/null; then
status_icon="${GREEN}${CHECK}${NC}"
status_text="${GREEN}running${NC}"
else
status_icon="${RED}${CROSS}${NC}"
status_text="${RED}stopped${NC}"
stopped+=("$svc")
stopped_labels+=("$label")
all_ok=false
fi
# Check if enabled at boot
if systemctl is-enabled --quiet "$svc" 2>/dev/null; then
enabled_icon="${GREEN}boot${NC}"
else
enabled_icon="${YELLOW}manual${NC}"
not_enabled+=("$svc")
not_enabled_labels+=("$label")
all_ok=false
fi
echo -e " ${status_icon} ${BOLD}${label}${NC}"
echo -e " Status: ${status_text} | Startup: ${enabled_icon}"
echo
done
separator
if $all_ok; then
echo
log "${GREEN}All services are running and enabled at boot${NC}"
echo
return
fi
# Offer to start stopped services
if [[ ${#stopped[@]} -gt 0 ]]; then
echo
warn "${#stopped[@]} service(s) not running: ${BOLD}${stopped_labels[*]}${NC}"
if confirm "Start all stopped services now?"; then
for i in "${!stopped[@]}"; do
local svc="${stopped[$i]}"
local label="${stopped_labels[$i]}"
info "Starting ${label}..."
if systemctl start "$svc" 2>&1 | tee -a "$LOG_FILE"; then
log "${label} started"
else
warn "Failed to start ${label}. Check: journalctl -u ${svc}"
fi
done
fi
fi
# Offer to enable services at boot
if [[ ${#not_enabled[@]} -gt 0 ]]; then
echo
warn "${#not_enabled[@]} service(s) not enabled at boot: ${BOLD}${not_enabled_labels[*]}${NC}"
if confirm "Enable all services to start automatically on boot?"; then
for i in "${!not_enabled[@]}"; do
local svc="${not_enabled[$i]}"
local label="${not_enabled_labels[$i]}"
if systemctl enable "$svc" 2>&1 | tee -a "$LOG_FILE"; then
log "${label} enabled at boot"
else
warn "Failed to enable ${label}."
fi
done
fi
fi
# Final status recheck
echo
separator
echo -e " ${BOLD}${WHITE}Updated Status${NC}"
echo
for i in "${!services[@]}"; do
local svc="${services[$i]}"
local label="${labels[$i]}"
local running="false"
local enabled="false"
systemctl is-active --quiet "$svc" 2>/dev/null && running="true"
systemctl is-enabled --quiet "$svc" 2>/dev/null && enabled="true"
local icon="${RED}${CROSS}${NC}"
[[ "$running" == "true" ]] && icon="${GREEN}${CHECK}${NC}"
local boot="${YELLOW}manual${NC}"
[[ "$enabled" == "true" ]] && boot="${GREEN}boot${NC}"
echo -e " ${icon} ${label} ${DIM}|${NC} ${boot}"
done
echo
separator
echo
}
main_menu() {
show_banner
separator
echo -e " ${BOLD}${WHITE}ACTIONS${NC}"
echo
echo -e " ${BOLD}${GREEN}1${NC} | Create a new site"
echo -e " ${BOLD}${CYAN}2${NC} | Edit a site"
echo -e " ${BOLD}${BLUE}3${NC} | List all sites"
echo -e " ${BOLD}${YELLOW}4${NC} | Renew SSL certificates"
echo -e " ${BOLD}${MAGENTA}5${NC} | Setup SSL auto-renewal"
echo -e " ${BOLD}${WHITE}6${NC} | Backup Manager"
echo -e " ${BOLD}${RED}7${NC} | Delete a site"
echo -e " ${BOLD}${CYAN}8${NC} | Service Manager"
echo -e " ${DIM}9${NC} | Exit"
echo
separator
echo -ne " ${CYAN}${ARROW}${NC} Choose an option ${DIM}[1-9]${NC}: "
read -r choice
case "$choice" in
1) create_site ;;
2) edit_site ;;
3) list_sites; echo; main_menu ;;
4) renew_ssl; echo; main_menu ;;
5) setup_ssl_auto_renewal; echo; main_menu ;;
6) manage_backups; echo; main_menu ;;
7) delete_site; echo; main_menu ;;
8) manage_services; echo; main_menu ;;
9) echo -e "\n ${DIM}Goodbye.${NC}\n"; exit 0 ;;
*) warn "Invalid option."; main_menu ;;
esac
}
# ── Site Type Menu ───────────────────────────────────────────
site_type_menu() {
header "Select Site Type"
echo -e " ${BOLD}${GREEN}1${NC} | ${BOLD}Static${NC} ${DIM}— HTML / CSS / JS${NC}"
echo -e " ${BOLD}${BLUE}2${NC} | ${BOLD}WordPress${NC} ${DIM}— Full WP install with DB${NC}"
echo -e " ${BOLD}${MAGENTA}3${NC} | ${BOLD}PHP${NC} ${DIM}— Custom PHP application${NC}"
echo -e " ${BOLD}${YELLOW}4${NC} | ${BOLD}Reverse Proxy${NC} ${DIM}— Node.js, Python, Go, etc.${NC}"
echo
echo -ne " ${CYAN}${ARROW}${NC} Choose a type ${DIM}[1-4]${NC}: "
read -r type_choice
case "$type_choice" in
1) SITE_TYPE="static" ;;
2) SITE_TYPE="wordpress" ;;
3) SITE_TYPE="php" ;;
4) SITE_TYPE="proxy" ;;
*) warn "Invalid option."; site_type_menu ;;
esac
log "Site type: ${BOLD}${SITE_TYPE}${NC}"
}
# ── Gather Site Info ─────────────────────────────────────────
gather_info() {
header "Site Configuration"
# NOTE: IS_LOCAL is already set by ask_local_or_public() called earlier
# Domain
if $IS_LOCAL; then
echo -ne " ${CYAN}${ARROW}${NC} Local domain ${DIM}(e.g. myapp.local, mysite.test)${NC}: "
else
echo -ne " ${CYAN}${ARROW}${NC} Domain name ${DIM}(e.g. example.com)${NC}: "
fi
read -r DOMAIN
DOMAIN="${DOMAIN,,}" # lowercase
# Auto-append .local if user typed a bare name for local sites
if $IS_LOCAL && [[ ! "$DOMAIN" == *.* ]]; then
DOMAIN="${DOMAIN}.local"
info "Auto-appended .local -> ${BOLD}${DOMAIN}${NC}"
fi
validate_domain "$DOMAIN"
# Warn if mismatch between choice and TLD
if $IS_LOCAL && ! is_local_domain "$DOMAIN"; then
warn "${DOMAIN} doesn't look like a local domain (.local, .test, .localhost)."
confirm "Continue anyway?" || { warn "Aborted."; main_menu; }
fi
if ! $IS_LOCAL && is_local_domain "$DOMAIN"; then
warn "${DOMAIN} looks like a local domain but you chose public."
if confirm "Switch to local mode?"; then
IS_LOCAL=true
fi
fi
SITE_DIR="${SITES_ROOT}/${DOMAIN}"
if [[ -d "$SITE_DIR" ]]; then
error "Site ${BOLD}${DOMAIN}${NC} already exists at ${SITE_DIR}"
fi
# www redirect (skip for local -- not useful)
HANDLE_WWW=false
if ! $IS_LOCAL; then
if confirm "Also handle www.${DOMAIN}?"; then
HANDLE_WWW=true
fi
fi
# Proxy port
if [[ "$SITE_TYPE" == "proxy" ]]; then
echo -ne " ${CYAN}${ARROW}${NC} Backend port ${DIM}(e.g. 3000)${NC}: "
read -r PROXY_PORT
validate_port "$PROXY_PORT"
fi
# SSL (skip for local sites)
SETUP_SSL=false
if $IS_LOCAL; then
info "SSL skipped for local domain (use http://${DOMAIN})"
else
if confirm "Set up SSL with Let's Encrypt?"; then
SETUP_SSL=true
echo -ne " ${CYAN}${ARROW}${NC} Email for SSL certificate: "
read -r SSL_EMAIL
validate_email "$SSL_EMAIL"
fi
fi
# Summary before proceeding
echo
separator
echo -e " ${BOLD}${WHITE}Configuration Summary${NC}"
echo -e " Domain: ${BOLD}${DOMAIN}${NC}"
echo -e " Type: ${BOLD}${SITE_TYPE}${NC}"
echo -e " Mode: ${BOLD}$( $IS_LOCAL && echo "LOCAL (127.0.0.1)" || echo "PUBLIC" )${NC}"
echo -e " WWW: ${HANDLE_WWW}"
echo -e " SSL: ${SETUP_SSL}"
echo -e " Path: ${SITE_DIR}"
[[ "$SITE_TYPE" == "proxy" ]] && echo -e " Backend: 127.0.0.1:${PROXY_PORT}"
separator
echo
confirm "Proceed with this configuration?" || { warn "Aborted."; main_menu; }
}
# ── Create Directories ───────────────────────────────────────
create_directories() {
info "Creating site directories..."
mkdir -p "${SITE_DIR}"/{public,logs,backups}
# nginx (${WEB_USER}) needs to traverse the home directory
chmod o+x "/home/${REAL_USER}"
chown -R "${WEB_USER}:${WEB_USER}" "${SITE_DIR}/public"
chown -R "${REAL_USER}:${WEB_USER}" "${SITE_DIR}/logs"
chown -R "${REAL_USER}:${WEB_USER}" "${SITE_DIR}/backups"
chmod -R 755 "$SITE_DIR"
log "Directories created at ${DIM}${SITE_DIR}${NC}"
}
# ── Database Setup ───────────────────────────────────────────
setup_database() {
header "Database Setup"
DB_NAME="${DOMAIN//[.-]/_}"
DB_USER="${DB_NAME:0:16}_usr"
DB_PASS=$(openssl rand -base64 24 | tr -dc 'A-Za-z0-9' | head -c 24)
# Check MariaDB/MySQL is running
if ! systemctl is-active --quiet mariadb 2>/dev/null && ! systemctl is-active --quiet mysql 2>/dev/null; then
warn "MariaDB/MySQL is not running. Attempting to start..."
systemctl start mariadb 2>/dev/null || systemctl start mysql 2>/dev/null || \
error "Could not start database server. Start it manually and re-run."
fi
info "Creating database: ${BOLD}${DB_NAME}${NC}"
mysql -e "CREATE DATABASE IF NOT EXISTS \`${DB_NAME}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" || \
error "Failed to create database. Check MySQL/MariaDB."
mysql -e "CREATE USER IF NOT EXISTS '${DB_USER}'@'localhost' IDENTIFIED BY '${DB_PASS}';"
mysql -e "GRANT ALL PRIVILEGES ON \`${DB_NAME}\`.* TO '${DB_USER}'@'localhost';"
mysql -e "FLUSH PRIVILEGES;"
# Save credentials (restricted permissions)
cat > "${SITE_DIR}/db-credentials.txt" <<EOF
======================================
DATABASE CREDENTIALS
======================================
DB Name: ${DB_NAME}
DB User: ${DB_USER}
DB Password: ${DB_PASS}
DB Host: localhost
Generated: $(date)
WARNING: Keep this file secure!
EOF
chmod 600 "${SITE_DIR}/db-credentials.txt"
chown "${REAL_USER}:${REAL_USER}" "${SITE_DIR}/db-credentials.txt"
log "Database ${BOLD}${DB_NAME}${NC} created"
log "Credentials saved to ${DIM}db-credentials.txt${NC}"
}
# ── Install WordPress ────────────────────────────────────────
install_wordpress() {
header "Installing WordPress"
local tmp_dir
tmp_dir=$(mktemp -d)
info "Downloading WordPress..."
wget -q https://wordpress.org/latest.tar.gz -O "${tmp_dir}/wordpress.tar.gz" &
spinner $! "Downloading WordPress..."
if [[ ! -f "${tmp_dir}/wordpress.tar.gz" ]]; then
rm -rf "$tmp_dir"
error "Failed to download WordPress. Check your internet connection."
fi
tar -xzf "${tmp_dir}/wordpress.tar.gz" -C "$tmp_dir"
cp -r "${tmp_dir}/wordpress/." "${SITE_DIR}/public/"
rm -rf "$tmp_dir"
# Configure wp-config.php
cp "${SITE_DIR}/public/wp-config-sample.php" "${SITE_DIR}/public/wp-config.php"
sed -i "s/database_name_here/${DB_NAME}/" "${SITE_DIR}/public/wp-config.php"
sed -i "s/username_here/${DB_USER}/" "${SITE_DIR}/public/wp-config.php"
sed -i "s/password_here/${DB_PASS}/" "${SITE_DIR}/public/wp-config.php"
# Allow WordPress to write directly without FTP prompt
# This is needed because SFTP jailing changes ownership away from ${WEB_USER}
if ! grep -q "FS_METHOD" "${SITE_DIR}/public/wp-config.php"; then
sed -i "/table_prefix/a\\
\\
/** Force direct filesystem writes (no FTP prompt) */\\
define('FS_METHOD', 'direct');" "${SITE_DIR}/public/wp-config.php"
log "FS_METHOD set to 'direct' (no FTP prompt)"
fi
# Generate security keys
info "Fetching WordPress security salts..."
local SALT
SALT=$(curl -sS --max-time 10 https://api.wordpress.org/secret-key/1.1/salt/ 2>/dev/null) || true
if [[ -n "$SALT" ]] && [[ "$SALT" == *"define"* ]]; then
# Remove all placeholder key lines
sed -i "/define( 'AUTH_KEY'/d" "${SITE_DIR}/public/wp-config.php"
sed -i "/define( 'SECURE_AUTH_KEY'/d" "${SITE_DIR}/public/wp-config.php"
sed -i "/define( 'LOGGED_IN_KEY'/d" "${SITE_DIR}/public/wp-config.php"
sed -i "/define( 'NONCE_KEY'/d" "${SITE_DIR}/public/wp-config.php"
sed -i "/define( 'AUTH_SALT'/d" "${SITE_DIR}/public/wp-config.php"
sed -i "/define( 'SECURE_AUTH_SALT'/d" "${SITE_DIR}/public/wp-config.php"
sed -i "/define( 'LOGGED_IN_SALT'/d" "${SITE_DIR}/public/wp-config.php"
sed -i "/define( 'NONCE_SALT'/d" "${SITE_DIR}/public/wp-config.php"
# Insert real salts after the "put your unique phrase" comment
local tmp_conf
tmp_conf=$(mktemp)
awk -v salts="$SALT" '
/put your unique phrase/ { print; print salts; next }
{ print }
' "${SITE_DIR}/public/wp-config.php" > "$tmp_conf"
if ! mv "$tmp_conf" "${SITE_DIR}/public/wp-config.php"; then
warn "Failed to update wp-config.php with security salts. Check ${tmp_conf}"
else
log "WordPress security salts injected"
fi
else
warn "Could not fetch security salts. Update them manually in wp-config.php"
fi
# Set correct permissions
find "${SITE_DIR}/public" -type d -exec chmod 755 {} +
find "${SITE_DIR}/public" -type f -exec chmod 644 {} +
chown -R ${WEB_USER}:${WEB_USER} "${SITE_DIR}/public"
# Tighten wp-config.php — contains DB credentials and salts
chmod 640 "${SITE_DIR}/public/wp-config.php" 2>/dev/null || true
log "WordPress installed successfully"
}
# ── Static Placeholder ───────────────────────────────────────
create_static_placeholder() {
cat > "${SITE_DIR}/public/index.html" <<EOF
<!DOCTYPE html>
<html lang="en">