-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathsamnet.sh
More file actions
executable file
·8313 lines (7015 loc) · 326 KB
/
Copy pathsamnet.sh
File metadata and controls
executable file
·8313 lines (7015 loc) · 326 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
# ══════════════════════════════════════════════════════════════════════════════
# SamNet-WG Unified Manager, Installer & CLI/TUI
# Version: 1.0.3
# License: MIT
#
# This is the SINGLE unified script that handles:
# - Zero-touch installation
# - Step-by-step wizard
# - Full TUI management interface
# - All CLI operations
# - System repair and maintenance
# ══════════════════════════════════════════════════════════════════════════════
# Enabled UTF-8 for TUI
export LC_ALL=C.UTF-8
# set -euo pipefail
# ══════════════════════════════════════════════════════════════════════════════
# 1. GLOBAL CONFIGURATION
# ══════════════════════════════════════════════════════════════════════════════
readonly SAMNET_VERSION="1.0.4"
readonly APP_NAME="SamNet-WG"
# ══════════════════════════════════════════════════════════════════════════════
# 1.5 INTEGRITY & SELF-HEALING
# ══════════════════════════════════════════════════════════════════════════════
# Only run file-based checks if we're executing from a file (not piped via curl)
if [[ -f "$0" ]]; then
# 1. Fix line endings if saved on Windows (CRLF -> LF)
if grep -q $'\r' "$0" 2>/dev/null; then
sed -i 's/\r$//' "$0"
exec "$0" "$@"
fi
# 2. Verify script syntax before doing any work
check_integrity() {
if ! bash -n "$0" 2>/tmp/samnet-syntax.tmp; then
echo -e "\033[1;31m"
echo "╔══════════════════════════════════════════════════════════════════════╗"
echo "║ CRITICAL ERROR: SCRIPT SYNTAX CORRUPTED ║"
echo "╚══════════════════════════════════════════════════════════════════════╝"
echo -e "\033[0m"
echo "A local modification to samnet.sh has introduced a syntax error."
echo "Script execution aborted to prevent system state corruption."
echo ""
echo "Error Details:"
cat /tmp/samnet-syntax.tmp
echo ""
rm -f /tmp/samnet-syntax.tmp
exit 1
fi
rm -f /tmp/samnet-syntax.tmp
}
check_integrity
fi
readonly TAGLINE="WireGuard Orchestrator & Management Platform"
# Trap terminal Resize
trap 'needs_refresh=true' SIGWINCH
# Paths (samnet-wg specific to avoid conflicts with other samnet products)
readonly DB_PATH="/var/lib/samnet-wg/samnet.db"
readonly WG_CONF="/etc/wireguard/wg0.conf"
readonly TRIGGER_FILE="/var/lib/samnet-wg/reconcile.trigger"
readonly INSTALL_DIR="/opt/samnet"
readonly CRED_FILE="/root/.samnet-wg_initial_credentials"
# Update System
readonly REPO_URL="https://github.com/SamNet-dev/wg-orchestrator.git"
readonly UPDATE_BRANCH="${SAMNET_BRANCH:-main}"
# Note: REMOTE_VERSION_URL must be set after UPDATE_BRANCH is defined
REMOTE_VERSION_URL="https://raw.githubusercontent.com/SamNet-dev/wg-orchestrator/${UPDATE_BRANCH}/samnet.sh"
# State
NOCOLOR=false
INTERACTIVE=false
ZERO_TOUCH=false
TERM_COLS=80
TERM_ROWS=24
# Self-Location
if [[ -f "$INSTALL_DIR/samnet" && "$(realpath "$0" 2>/dev/null)" == "$INSTALL_DIR/samnet" ]]; then
DIR="$INSTALL_DIR"
else
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
fi
# ══════════════════════════════════════════════════════════════════════════════
# 2. SAMNET TERMINAL UI FRAMEWORK
# ══════════════════════════════════════════════════════════════════════════════
#
# A custom-built terminal UI system designed to make SamNet feel like
# professional infrastructure software, not a bash script.
#
# Design Philosophy:
# - Every screen is a composed layout, not printed text
# - Visual consistency across all interactions
# - Operator trust through polish and predictability
# - Retro-futuristic aesthetic with modern functionality
#
# ══════════════════════════════════════════════════════════════════════════════
# ─── Theme & Color Engine ─────────────────────────────────────────────────────
init_colors() {
if [[ "$NOCOLOR" == true ]] || ! [[ -t 1 ]]; then
# No-color mode: all color codes empty
T_RESET="" T_BOLD="" T_DIM="" T_ITALIC="" T_UNDERLINE="" T_BLINK="" T_REVERSE=""
T_BLACK="" T_RED="" T_GREEN="" T_YELLOW="" T_BLUE="" T_MAGENTA="" T_CYAN="" T_WHITE=""
T_ORANGE="" T_GRAY="" T_BG="" T_FG=""
# Legacy compatibility
C_RESET="" C_BOLD="" C_DIM="" C_RED="" C_GREEN="" C_YELLOW="" C_BLUE="" C_CYAN="" C_MAGENTA="" C_WHITE="" C_ORANGE=""
else
# SamNet Theme: Amber/Orange primary, Cyan accent, Dark background assumed
T_RESET=$'\033[0m'
T_BOLD=$'\033[1m'
T_DIM=$'\033[2m'
T_ITALIC=$'\033[3m'
T_UNDERLINE=$'\033[4m'
T_BLINK=$'\033[5m'
T_REVERSE=$'\033[7m'
# Core palette (256-color safe)
T_BLACK=$'\033[38;5;232m'
T_RED=$'\033[38;5;196m'
T_GREEN=$'\033[38;5;82m'
T_YELLOW=$'\033[38;5;220m'
T_BLUE=$'\033[38;5;39m'
T_MAGENTA=$'\033[38;5;201m'
T_CYAN=$'\033[38;5;51m'
T_WHITE=$'\033[38;5;255m'
T_ORANGE=$'\033[38;5;208m'
T_GRAY=$'\033[38;5;240m'
# Background accents
T_BG_HIGHLIGHT=$'\033[48;5;236m'
T_BG_SELECT=$'\033[48;5;238m'
T_BG_DANGER=$'\033[48;5;52m'
# Legacy compatibility
C_RESET="$T_RESET" C_BOLD="$T_BOLD" C_DIM="$T_DIM"
C_RED="$T_RED" C_GREEN="$T_GREEN" C_YELLOW="$T_YELLOW"
C_BLUE="$T_BLUE" C_CYAN="$T_CYAN" C_MAGENTA="$T_MAGENTA"
C_WHITE="$T_WHITE" C_ORANGE="$T_ORANGE"
fi
# Semantic colors - RETRO GREEN THEME
CLR_PRIMARY="$T_GREEN"
CLR_ACCENT="$T_CYAN"
CLR_SUCCESS="$T_GREEN"
CLR_WARNING="$T_YELLOW"
CLR_DANGER="$T_RED"
CLR_MUTED="$T_GRAY"
CLR_TEXT="$T_WHITE"
# Status indicators (consistent symbols)
ICON_OK="${T_GREEN}●${T_RESET}"
ICON_WARN="${T_YELLOW}●${T_RESET}"
ICON_FAIL="${T_RED}●${T_RESET}"
ICON_INFO="${T_CYAN}◆${T_RESET}"
ICON_ARROW="${T_GREEN}▸${T_RESET}"
ICON_CHECK="${T_GREEN}✓${T_RESET}"
ICON_CROSS="${T_RED}✗${T_RESET}"
ICON_DOT="${T_GRAY}·${T_RESET}"
# Legacy icons
SUCCESS_ICON="$ICON_CHECK"
ERROR_ICON="$ICON_CROSS"
WARN_ICON="${T_YELLOW}⚠${T_RESET}"
INFO_ICON="${T_CYAN}ℹ${T_RESET}"
}
# Helper: Normalize CIDR (e.g. 10.100.0.1/19 -> 10.100.0.0/19)
normalize_cidr() {
local raw=$1
[[ -z "$raw" ]] && echo "Not configured" && return
local ip=$(echo "$raw" | cut -d/ -f1)
local mask=$(echo "$raw" | cut -d/ -f2)
# If no mask, assume /32
if [[ "$ip" == "$mask" ]] || [[ -z "$mask" ]]; then mask=32; fi
# Very simple normalization for common privates
if [[ "$ip" =~ ^10\.|^172\.|^192\. ]]; then
local base=$(echo "$ip" | cut -d. -f1-3)
echo "${base}.0/${mask}"
else
echo "$raw"
fi
}
# Helper: UI Checkbox
ui_checkbox() {
if [[ "$1" == "true" ]]; then
printf "${T_GREEN} [x] ${T_RESET}"
else
printf "${T_DIM} [ ] ${T_RESET}"
fi
}
# ─── Terminal Control ─────────────────────────────────────────────────────────
get_term_size() {
if command -v tput &>/dev/null && [[ -t 1 ]]; then
TERM_COLS=$(tput cols 2>/dev/null) || TERM_COLS=80
TERM_ROWS=$(tput lines 2>/dev/null) || TERM_ROWS=24
else
TERM_COLS=80
TERM_ROWS=24
fi
# Minimum dimensions
[[ $TERM_COLS -lt 60 ]] && TERM_COLS=60
[[ $TERM_ROWS -lt 20 ]] && TERM_ROWS=20
}
ui_clear() { printf '\033[2J\033[H'; }
ui_hide_cursor() { printf '\033[?25l'; }
ui_show_cursor() { printf '\033[?25h'; }
ui_save_cursor() { printf '\033[s'; }
ui_restore_cursor() { printf '\033[u'; }
ui_move_to() { printf '\033[%d;%dH' "$1" "$2"; }
ui_clear_line() { printf '\033[2K'; }
ui_clear_to_end() { printf '\033[J'; }
# Alternate screen buffer - creates a separate "app space"
ui_enter_app() {
tput smcup 2>/dev/null || true # Enter alternate screen
ui_hide_cursor
stty -echo 2>/dev/null || true
trap 'ui_exit_app' EXIT INT TERM
}
ui_exit_app() {
ui_show_cursor
stty echo 2>/dev/null || true
tput rmcup 2>/dev/null || true # Exit alternate screen
printf "${T_RESET}"
}
# Ensure terminal state is restored on exit
ui_cleanup() {
ui_exit_app
}
# ─── Layout System ────────────────────────────────────────────────────────────
# Content area dimensions (accounting for header/footer)
LAYOUT_HEADER_HEIGHT=9
LAYOUT_FOOTER_HEIGHT=3
LAYOUT_CONTENT_START=$((LAYOUT_HEADER_HEIGHT + 1))
# Repeat a character N times (UTF-8 safe)
ui_repeat() {
local char="$1" count="$2"
local result=""
for ((i=0; i<count; i++)); do result+="$char"; done
printf "%s" "$result"
}
# Horizontal rule with optional label
ui_rule() {
local label="${1:-}"
local char="${2:-─}"
local width=$((TERM_COLS - 4))
if [[ -n "$label" ]]; then
local label_len=${#label}
local left_len=$(( (width - label_len - 2) / 2 ))
local right_len=$(( width - label_len - 2 - left_len ))
printf " ${T_WHITE}%s ${T_CYAN}${T_BOLD}%s${T_RESET}${T_WHITE} %s${T_RESET}\n" \
"$(ui_repeat "$char" $left_len)" "$label" "$(ui_repeat "$char" $right_len)"
else
printf " ${T_WHITE}%s${T_RESET}\n" "$(ui_repeat "$char" $width)"
fi
}
# ─── Header Component ─────────────────────────────────────────────────────────
ui_draw_header() {
local title="${1:-}"
ui_clear
# ASCII Banner - Retro Terminal Style
printf "${T_GREEN}${T_BOLD}"
cat << 'BANNER'
╔════════════════════════════════════════════════════════════════════╗
║ ███████╗ █████╗ ███╗ ███╗███╗ ██╗███████╗████████╗ ║
║ ██╔════╝██╔══██╗████╗ ████║████╗ ██║██╔════╝╚══██╔══╝ ║
║ ███████╗███████║██╔████╔██║██╔██╗ ██║█████╗ ██║ ║
║ ╚════██║██╔══██║██║╚██╔╝██║██║╚██╗██║██╔══╝ ██║ ║
║ ███████║██║ ██║██║ ╚═╝ ██║██║ ╚████║███████╗ ██║ ║
║ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝╚══════╝ ╚═╝ ║
╚════════════════════════════════════════════════════════════════════╝
BANNER
printf "${T_RESET}"
# Branding bar
printf " ${T_DIM}────────────────────────────────────────────────────────────────${T_RESET}\n"
printf " ${T_GREEN}${T_BOLD}By ${AUTHOR}${T_RESET} ${T_GRAY}│${T_RESET} ${T_CYAN}${WEBSITE}${T_RESET} ${T_GRAY}│${T_RESET} ${T_DIM}v${SAMNET_VERSION} - General Public Release${T_RESET}\n"
printf " ${T_WHITE}${TAGLINE}${T_RESET}\n"
printf " ${T_DIM}────────────────────────────────────────────────────────────────${T_RESET}\n"
# Screen title if provided
if [[ -n "$title" ]]; then
printf "\n ${T_GREEN}${T_BOLD}▸ %s${T_RESET}\n" "$title"
fi
printf "\n"
}
# Minimal header for sub-screens
ui_draw_header_mini() {
local title="$1"
ui_clear
printf " ${T_ORANGE}${T_BOLD}▸ SAMNET${T_RESET} ${T_GRAY}│${T_RESET} ${T_CYAN}%s${T_RESET}\n" "$title"
ui_rule
printf "\n"
}
# ─── Footer Component ─────────────────────────────────────────────────────────
ui_draw_footer() {
local hints="${1:-}"
local extra="${2:-}"
printf "\n"
ui_rule
printf " ${T_DIM}%s${T_RESET}" "$hints"
[[ -n "$extra" ]] && printf " ${T_GRAY}│${T_RESET} ${T_DIM}%s${T_RESET}" "$extra"
printf "\n"
}
# ─── Box Components ───────────────────────────────────────────────────────────
# Standard content box with title
# Standard content box with title (ASCII safe)
ui_box() {
local title="$1"
shift
local width=$((TERM_COLS - 8))
local inner_width=$((width - 4))
# Top border with title
printf " ${T_CYAN}+-${T_BOLD}${T_WHITE} %s ${T_RESET}${T_CYAN}" "$title"
printf -- "%s+${T_RESET}\n" "$(ui_repeat '-' $((width - ${#title} - 5)))"
# Content lines
for line in "$@"; do
printf " ${T_CYAN}|${T_RESET} ${T_WHITE}%-${inner_width}s${T_RESET} ${T_CYAN}|${T_RESET}\n" "$line"
done
# Bottom border
printf " ${T_CYAN}+%s+${T_RESET}\n" "$(ui_repeat '-' $((width - 2)))"
}
# Info box (blue accent)
# Info box (blue accent)
ui_box_info() {
local title="$1"
shift
local width=$((TERM_COLS - 8))
local inner_width=$((width - 4))
printf " ${T_BLUE}+-${T_BOLD} %s ${T_RESET}${T_BLUE}" "$title"
printf -- "%s+${T_RESET}\n" "$(ui_repeat '-' $((width - ${#title} - 5)))"
for line in "$@"; do
printf " ${T_BLUE}|${T_RESET} ${T_WHITE}%s${T_RESET}%*s${T_BLUE}|${T_RESET}\n" "$line" $((inner_width - ${#line})) ""
done
printf " ${T_BLUE}+%s+${T_RESET}\n" "$(ui_repeat '-' $((width - 2)))"
}
# Warning box (yellow accent)
# Warning box (yellow accent)
ui_box_warn() {
local title="$1"
shift
local width=$((TERM_COLS - 8))
printf " ${T_YELLOW}+-${T_BOLD}! %s ${T_RESET}${T_YELLOW}" "$title"
printf -- "%s+${T_RESET}\n" "$(ui_repeat '-' $((width - ${#title} - 6)))"
for line in "$@"; do
printf " ${T_YELLOW}|${T_RESET} ${T_YELLOW}%s${T_RESET}\n" "$line"
done
printf " ${T_YELLOW}+%s+${T_RESET}\n" "$(ui_repeat '-' $((width - 2)))"
}
# Danger box (red accent)
# Danger box (red accent)
ui_box_danger() {
local title="$1"
shift
local width=$((TERM_COLS - 8))
printf " ${T_RED}+=${T_BOLD}${T_BLINK}!${T_RESET}${T_RED}${T_BOLD} %s ${T_RESET}${T_RED}" "$title"
printf -- "%s+${T_RESET}\n" "$(ui_repeat '=' $((width - ${#title} - 6)))"
for line in "$@"; do
printf " ${T_RED}|${T_RESET} ${T_RED}${T_BOLD}%s${T_RESET}\n" "$line"
done
printf " ${T_RED}+%s+${T_RESET}\n" "$(ui_repeat '=' $((width - 2)))"
}
# ─── Status Badges ────────────────────────────────────────────────────────────
ui_status() {
local label="$1"
local state="$2"
local detail="${3:-}"
local icon value_color
case "$state" in
ok|online|active|running|pass)
icon="$ICON_OK"
value_color="$T_GREEN"
;;
warn|warning|degraded|slow)
icon="$ICON_WARN"
value_color="$T_YELLOW"
;;
fail|error|offline|stopped|critical)
icon="$ICON_FAIL"
value_color="$T_RED"
;;
*)
icon="$ICON_INFO"
value_color="$T_CYAN"
;;
esac
printf " %s %-18s ${value_color}%s${T_RESET}" "$icon" "$label" "$state"
[[ -n "$detail" ]] && printf " ${T_DIM}%s${T_RESET}" "$detail"
printf "\n"
}
# Compact status row (for dashboards)
ui_status_row() {
local items=("$@")
printf " "
for item in "${items[@]}"; do
IFS='=' read -r label state <<< "$item"
case "$state" in
ok|online|active) printf "${ICON_OK} %-10s " "$label" ;;
warn|degraded) printf "${ICON_WARN} %-10s " "$label" ;;
fail|offline) printf "${ICON_FAIL} %-10s " "$label" ;;
*) printf "${ICON_INFO} %-10s " "$label" ;;
esac
done
printf "\n"
}
# ─── Menu System ──────────────────────────────────────────────────────────────
# Single menu option
ui_menu_item() {
local key="$1"
local label="$2"
local desc="${3:-}"
local selected="${4:-false}"
if [[ "$selected" == "true" ]]; then
printf " ${T_BG_SELECT}${T_CYAN}${T_BOLD}[%s]${T_RESET}${T_BG_SELECT} ${T_WHITE}%-24s${T_RESET}${T_BG_SELECT} ${T_CYAN}%s${T_RESET}\n" "$key" "$label" "$desc"
else
printf " ${T_CYAN}${T_BOLD}[%s]${T_RESET} %-24s ${T_WHITE}%s${T_RESET}\n" "$key" "$label" "$desc"
fi
}
# Menu group header
ui_menu_group() {
local title="$1"
printf "\n ${T_ORANGE}${T_BOLD}%s${T_RESET}\n" "$title"
printf " ${T_GRAY}$(ui_repeat '─' 40)${T_RESET}\n"
}
# Separator between menu sections
ui_menu_sep() {
printf "\n"
}
# ─── Data Display ─────────────────────────────────────────────────────────────
# Key-value pair
ui_kv() {
local key="$1"
local value="$2"
local indent="${3:-4}"
printf "%*s${T_CYAN}%-14s${T_RESET} ${T_WHITE}%s${T_RESET}\n" "$indent" "" "$key:" "$value"
}
# Tree-style list item
ui_tree() {
local prefix="$1"
local label="$2"
local value="$3"
local last="${4:-false}"
if [[ "$last" == "true" ]]; then
printf " └─ ${T_GRAY}%-12s${T_RESET} ${T_WHITE}%s${T_RESET}\n" "$label" "$value"
else
printf " ├─ ${T_GRAY}%-12s${T_RESET} ${T_WHITE}%s${T_RESET}\n" "$label" "$value"
fi
}
# Table header
ui_table_header() {
local cols=("$@")
printf " ${T_BOLD}"
for col in "${cols[@]}"; do
printf "%-16s" "$col"
done
printf "${T_RESET}\n"
printf " ${T_GRAY}$(ui_repeat '─' $(( ${#cols[@]} * 16 )))${T_RESET}\n"
}
# Table row
ui_table_row() {
local cols=("$@")
printf " "
for col in "${cols[@]}"; do
printf "%-16s" "$col"
done
printf "\n"
}
# ─── Progress & Loading ───────────────────────────────────────────────────────
ui_progress() {
local label="$1"
local percent="$2"
local width=30
local filled=$(( percent * width / 100 ))
local empty=$(( width - filled ))
printf " %-20s ${T_CYAN}[" "$label"
printf "$(ui_repeat '#' $filled)"
printf "${T_WHITE}$(ui_repeat '.' $empty)"
printf "${T_CYAN}]${T_RESET} ${T_WHITE}%3d%%${T_RESET}\n" "$percent"
}
ui_spinner() {
local label="$1"
local chars='⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
local i=0
while true; do
printf "\r ${T_CYAN}%s${T_RESET} %s " "${chars:i:1}" "$label"
((i = (i + 1) % ${#chars}))
sleep 0.1
done
}
# ─── Input Components ─────────────────────────────────────────────────────────
ui_prompt() {
local label="$1"
local default="${2:-}"
local result
if [[ -n "$default" ]]; then
printf " ${T_CYAN}❯${T_RESET} %s ${T_WHITE}[%s]${T_RESET}: " "$label" "$default" >&2
else
printf " ${T_CYAN}❯${T_RESET} %s: " "$label" >&2
fi
stty echo 2>/dev/null
read -r result
stty -echo 2>/dev/null
echo "${result:-$default}"
}
ui_confirm() {
local message="$1"
local response
printf " ${T_YELLOW}⚠${T_RESET} %s ${T_DIM}[y/N]${T_RESET} " "$message"
read -rsn1 response
printf "%s\n" "$response"
if [[ "$response" == "y" || "$response" == "Y" ]]; then
return 0
else
return 1
fi
}
ui_confirm_danger() {
local action="$1"
local code=$(printf "%04d" $((RANDOM % 10000)))
printf "\n"
ui_box_danger "DANGER ZONE" \
"You are about to: $action" \
"" \
"This action cannot be undone."
printf "\n To confirm, type: ${T_BOLD}${T_RED}%s${T_RESET}\n" "$code"
printf " ${T_CYAN}❯${T_RESET} "
local input
read -r input
[[ "$input" == "$code" ]]
}
ui_wait_key() {
local message="${1:-Press any key to continue...}"
printf "\n ${T_DIM}%s${T_RESET}" "$message"
read -rsn1
printf "\n"
}
ui_read_key() {
local key
# Only use timeout when Web UI is enabled (for sync updates)
# CLI-only mode doesn't need polling since there's no Web UI to sync with
if [[ "$(db_get_config web_ui_enabled)" == "true" ]]; then
read -rsn1 -t 7 key 2>/dev/null
else
read -rsn1 key 2>/dev/null
fi
echo "$key"
}
# Alias for compatibility
read_key_static() {
local key
read -rsn1 key 2>/dev/null
echo "$key"
}
# ─── Help Overlay ─────────────────────────────────────────────────────────────
ui_help_overlay() {
local title="$1"
shift
local lines=("$@")
ui_draw_header_mini "Help: $title"
ui_box_info "About This Screen" "${lines[@]}"
printf "\n"
ui_menu_group "Keyboard Shortcuts"
ui_kv "[B/Esc]" "Go back"
ui_kv "[Q]" "Quit application"
ui_kv "[?]" "Show this help"
ui_kv "[/]" "Command palette"
ui_wait_key
}
# ─── Messages & Logging ───────────────────────────────────────────────────────
log_info() { printf " ${T_CYAN}ℹ${T_RESET} %s\n" "$1"; }
log_success() { printf " ${T_GREEN}✓${T_RESET} %s\n" "$1"; }
log_warn() { printf " ${T_YELLOW}⚠${T_RESET} ${T_YELLOW}%s${T_RESET}\n" "$1"; }
log_error() { printf " ${T_RED}✗${T_RESET} ${T_RED}%s${T_RESET}\n" "$1" >&2; }
log_step() { printf " ${T_CYAN}▸${T_RESET} %s\n" "$1"; }
exit_with_error() {
log_error "$1"
printf "\n ${T_RED}Aborted.${T_RESET}\n"
exit 1
}
# ─── Legacy Compatibility Layer ───────────────────────────────────────────────
clear_screen() { ui_clear; }
hide_cursor() { ui_hide_cursor; }
show_cursor() { ui_show_cursor; }
show_banner() { ui_draw_header; }
section() { printf "\n ${T_ORANGE}${T_BOLD}▸ %s${T_RESET}\n" "$1"; ui_rule; }
menu_option() { ui_menu_item "$@"; }
show_footer() { ui_draw_footer "$@"; }
draw_box() { ui_box "$@"; }
prompt() { ui_prompt "$@"; }
confirm() { ui_confirm "$@"; }
wait_key() { ui_wait_key "$@"; }
read_key() { ui_read_key; }
draw_line() { ui_repeat "${1:-─}" "${2:-$TERM_COLS}"; }
# ─── Help Screen ──────────────────────────────────────────────────────────────
show_help_screen() {
while true; do
ui_clear
printf "${T_GREEN}${T_BOLD}"
cat << 'HELP_BANNER'
╔══════════════════════════════════════════════════════════════════════╗
║ SAMNET HELP CENTER ║
╚══════════════════════════════════════════════════════════════════════╝
HELP_BANNER
printf "${T_RESET}\n"
printf " ${T_CYAN}${T_BOLD}NAVIGATION${T_RESET}\n"
printf " ${T_WHITE}────────────────────────────────────────────────────────${T_RESET}\n"
printf " ${T_GREEN}↑/↓${T_RESET} or ${T_GREEN}j/k${T_RESET} Navigate menu items\n"
printf " ${T_GREEN}Enter${T_RESET} Select/confirm\n"
printf " ${T_GREEN}B${T_RESET} or ${T_GREEN}Esc${T_RESET} Go back\n"
printf " ${T_GREEN}Q${T_RESET} Quit application\n"
printf " ${T_GREEN}H${T_RESET} Show this help\n"
printf " ${T_GREEN}A${T_RESET} About SamNet\n\n"
printf " ${T_CYAN}${T_BOLD}PEER MANAGEMENT${T_RESET}\n"
printf " ${T_WHITE}────────────────────────────────────────────────────────${T_RESET}\n"
printf " ${T_WHITE}Add Peer${T_RESET} Create a new VPN client\n"
printf " ${T_WHITE}List Peers${T_RESET} View all connected clients\n"
printf " ${T_WHITE}Remove Peer${T_RESET} Delete a client and revoke access\n"
printf " ${T_WHITE}Show QR Code${T_RESET} Display QR for mobile setup\n\n"
printf " ${T_CYAN}${T_BOLD}SYSTEM OPERATIONS${T_RESET}\n"
printf " ${T_WHITE}────────────────────────────────────────────────────────${T_RESET}\n"
printf " ${T_WHITE}Status${T_RESET} View WireGuard tunnel status\n"
printf " ${T_WHITE}Config${T_RESET} Edit server configuration\n"
printf " ${T_WHITE}Logs${T_RESET} View system logs\n"
printf " ${T_WHITE}Restart${T_RESET} Restart WireGuard service\n\n"
printf " ${T_CYAN}${T_BOLD}ADVANCED TOOLS${T_RESET}\n"
printf " ${T_WHITE}────────────────────────────────────────────────────────${T_RESET}\n"
printf " ${T_WHITE}Troubleshooter${T_RESET} Auto-detect and fix issues\n"
printf " ${T_WHITE}Repair Wizard${T_RESET} Rebuild critical configs\n"
printf " ${T_WHITE}DDNS Setup${T_RESET} Configure Dynamic DNS\n"
printf " ${T_WHITE}Watch Mode${T_RESET} Live traffic dashboard\n"
printf " ${T_WHITE}Benchmarks${T_RESET} Test system performance\n"
printf " ${T_WHITE}Export Diag${T_RESET} Generate support bundle\n\n"
printf " ${T_CYAN}${T_BOLD}WEB UI${T_RESET}\n"
printf " ${T_WHITE}────────────────────────────────────────────────────────${T_RESET}\n"
printf " ${T_WHITE}Default Username:${T_RESET} ${T_GREEN}admin${T_RESET}\n"
printf " ${T_WHITE}Default Password:${T_RESET} ${T_GREEN}changeme${T_RESET}\n"
printf " ${T_WHITE}Access:${T_RESET} HTTP on port 80 (local network)\n"
printf " ${T_DIM}Enable via: Main Menu → Install/Repair → Enable Web UI${T_RESET}\n\n"
printf " ${T_CYAN}${T_BOLD}PORTS REQUIRED${T_RESET}\n"
printf " ${T_WHITE}────────────────────────────────────────────────────────${T_RESET}\n"
printf " ${T_WHITE}51820/UDP${T_RESET} WireGuard VPN traffic\n"
printf " ${T_WHITE}80/TCP${T_RESET} Web UI (optional, if enabled)\n\n"
printf " ${T_CYAN}${T_BOLD}COMMAND LINE${T_RESET}\n"
printf " ${T_WHITE}────────────────────────────────────────────────────────${T_RESET}\n"
printf " ${T_WHITE}samnet${T_RESET} Launch interactive TUI\n"
printf " ${T_WHITE}samnet --update${T_RESET} Check for and apply updates\n"
printf " ${T_WHITE}samnet --status${T_RESET} Show system status\n"
printf " ${T_WHITE}samnet -z${T_RESET} Zero-touch install\n"
printf " ${T_WHITE}samnet --uninstall${T_RESET} Remove SamNet-WG\n\n"
ui_draw_footer "[B] Back"
local key=$(read_key_static)
case "$key" in
b|B|$'\x1b'|q|Q) return ;;
esac
done
}
# ─── About Screen ─────────────────────────────────────────────────────────────
show_about_screen() {
while true; do
ui_clear
printf "${T_GREEN}${T_BOLD}"
cat << 'ABOUT_BANNER'
╔══════════════════════════════════════════════════════════════════════╗
║ ███████╗ █████╗ ███╗ ███╗███╗ ██╗███████╗████████╗ ║
║ ██╔════╝██╔══██╗████╗ ████║████╗ ██║██╔════╝╚══██╔══╝ ║
║ ███████╗███████║██╔████╔██║██╔██╗ ██║█████╗ ██║ ║
║ ╚════██║██╔══██║██║╚██╔╝██║██║╚██╗██║██╔══╝ ██║ ║
║ ███████║██║ ██║██║ ╚═╝ ██║██║ ╚████║███████╗ ██║ ║
║ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝╚══════╝ ╚═╝ ║
╚══════════════════════════════════════════════════════════════════════╝
ABOUT_BANNER
printf "${T_RESET}\n"
printf " ${T_CYAN}${T_BOLD}WireGuard Orchestrator & Management Platform${T_RESET}\n\n"
printf " ${T_WHITE}Version:${T_RESET} ${T_GREEN}${SAMNET_VERSION}${T_RESET}\n"
printf " ${T_WHITE}Author:${T_RESET} ${T_CYAN}${AUTHOR}${T_RESET}\n"
printf " ${T_WHITE}Website:${T_RESET} ${T_CYAN}${WEBSITE}${T_RESET}\n"
printf " ${T_WHITE}License:${T_RESET} ${T_DIM}MIT License${T_RESET}\n\n"
printf " ${T_WHITE}────────────────────────────────────────────────────────${T_RESET}\n\n"
printf " ${T_DIM}SamNet-WG is an enterprise-grade WireGuard VPN management${T_RESET}\n"
printf " ${T_DIM}platform designed for simplicity and security. It provides${T_RESET}\n"
printf " ${T_DIM}zero-touch installation, automatic peer management, and a${T_RESET}\n"
printf " ${T_DIM}beautiful terminal interface for self-hosted VPN servers.${T_RESET}\n\n"
printf " ${T_WHITE}────────────────────────────────────────────────────────${T_RESET}\n\n"
printf " ${T_CYAN}${T_BOLD}System Locations:${T_RESET}\n"
printf " ${T_WHITE}Install Dir:${T_RESET} ${T_DIM}/opt/samnet${T_RESET}\n"
printf " ${T_WHITE}Database:${T_RESET} ${T_DIM}/var/lib/samnet-wg${T_RESET}\n"
printf " ${T_WHITE}Logs:${T_RESET} ${T_DIM}/var/log/samnet-wg${T_RESET}\n"
printf " ${T_WHITE}WG Config:${T_RESET} ${T_DIM}/etc/wireguard${T_RESET}\n"
printf " ${T_WHITE}Auth File:${T_RESET} ${T_DIM}/opt/samnet/credentials.txt${T_RESET}\n\n"
printf " ${T_GREEN}★${T_RESET} ${T_DIM}Built with love for the self-hosting community${T_RESET}\n"
printf " ${T_GREEN}★${T_RESET} ${T_DIM}Powered by WireGuard® - the modern VPN protocol${T_RESET}\n"
printf " ${T_GREEN}★${T_RESET} ${T_DIM}100%% Open Source - Audit the code yourself${T_RESET}\n\n"
ui_draw_footer "[B] Back"
local key=$(read_key)
case "$key" in
b|B|$'\x1b'|q|Q) return ;;
esac
done
}
# ══════════════════════════════════════════════════════════════════════════════
# 3. SECURITY & VALIDATION
# ══════════════════════════════════════════════════════════════════════════════
# Early dependency check - runs BEFORE TUI starts
ensure_early_dependencies() {
local missing=()
# Critical dependencies that must be present
command -v sqlite3 &>/dev/null || missing+=("sqlite3")
command -v curl &>/dev/null || missing+=("curl")
command -v ip &>/dev/null || missing+=("iproute2")
command -v wg &>/dev/null || missing+=("wireguard-tools")
if [[ ${#missing[@]} -gt 0 ]]; then
echo -e "${T_GREEN}${T_BOLD}[SamNet]${T_RESET} Checking dependencies..."
echo -e "${T_DIM} Missing: ${missing[*]}${T_RESET}"
echo -e "${T_GREEN} Installing required packages (this may take a moment)...${T_RESET}"
# Detect package manager and install with PROGRESS
if command -v apt-get &>/dev/null; then
apt-get update
apt-get install -y "${missing[@]}"
elif command -v dnf &>/dev/null; then
dnf install -y "${missing[@]}"
elif command -v yum &>/dev/null; then
yum install -y "${missing[@]}"
elif command -v pacman &>/dev/null; then
pacman -Sy --noconfirm "${missing[@]}"
else
echo -e "${T_RED}ERROR: Could not detect package manager.${T_RESET}"
echo "Please install manually: ${missing[*]}"
exit 1
fi
if [[ $? -eq 0 ]]; then
echo -e "${T_GREEN}✓ Dependencies installed successfully${T_RESET}"
else
echo -e "${T_RED}✗ Installation failed. Please check your internet connection or package manager.${T_RESET}"
exit 1
fi
fi
}
check_root() {
if [[ $EUID -ne 0 ]]; then
echo -e "${C_RED}ERROR: Must run as root (sudo)${C_RESET}" >&2
exit 1
fi
}
detect_public_ip() {
local sources=(
"https://ifconfig.me"
"https://icanhazip.com"
"https://ipinfo.io/ip"
"https://api.ipify.org"
)
local ips=()
for url in "${sources[@]}"; do
local ip=$(curl --silent --max-time 5 -4 "$url" 2>/dev/null | tr -d '[:space:]')
if [[ "$ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
ips+=("$ip")
fi
done
# Fallback to local interface IP detection if external services fail
if [[ ${#ips[@]} -lt 2 ]]; then
[[ -n "${SAMNET_WAN_IP:-}" ]] && echo "$SAMNET_WAN_IP" && return 0
# Local interface fallback
local local_ip=$(ip route get 8.8.8.8 2>/dev/null | awk '{print $7; exit}')
if [[ "$local_ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
log_warn "Using local interface IP as fallback: $local_ip"
echo "$local_ip"
return 0
fi
return 1
fi
printf '%s\n' "${ips[@]}" | sort | uniq -c | sort -rn | head -1 | awk '{print $2}'
}
validate_interface() {
local iface="$1"
[[ "$iface" =~ ^[a-zA-Z0-9_-]+$ ]] || return 1
ip link show "$iface" &>/dev/null
}
run_preflight_checks() {
log_info "Running pre-flight checks..."
local failed=0
# Check for 1GB free (500MB base + 500MB for Docker images)
# Check for 1GB free (500MB base + 500MB for Docker images)
local free_mb=$(df -m /var 2>/dev/null | tail -1 | awk '{print $4}')
if [[ ${free_mb:-0} -lt 1000 ]]; then
log_warn "Insufficient disk: ${free_mb}MB (need 1GB+ for Docker images)"
log_info "Attempting to free space..."
docker image prune -f >/dev/null 2>&1 || true
fi
# Critical checks (must pass)
if ! lsmod 2>/dev/null | grep -q wireguard && ! modprobe wireguard 2>/dev/null; then
log_error "WireGuard module required but not available"
((failed++))
fi
for port in 51820 80 8080; do
if ss -tuln 2>/dev/null | grep -q ":$port "; then
log_warn "Port $port in use"
fi
done
if ! curl --silent --max-time 5 https://google.com &>/dev/null; then
log_warn "No internet connectivity"
fi
[[ $failed -gt 0 ]] && return 1
log_success "Pre-flight checks passed"
}
sanitize_input() { echo "${1//\'/\'\'}"; }
validate_key() {
[[ "$1" =~ ^[a-zA-Z0-9_]+$ ]] || { log_error "Invalid key: $1"; return 1; }
}
# ══════════════════════════════════════════════════════════════════════════════
# 4. DATABASE ENGINE
# ══════════════════════════════════════════════════════════════════════════════
ensure_db_init() {
mkdir -p "$(dirname "$DB_PATH")" && chmod 700 "$(dirname "$DB_PATH")"
if [[ ! -f "$DB_PATH" ]]; then
log_info "Initializing database schema..."
sqlite3 -batch "$DB_PATH" <<SQL || exit_with_error "Failed to initialize database schema"
CREATE TABLE IF NOT EXISTS system_config (key TEXT PRIMARY KEY, value TEXT);
CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, role TEXT NOT NULL DEFAULT 'viewer', failed_attempts INTEGER DEFAULT 0, lockout_until DATETIME);
CREATE TABLE IF NOT EXISTS sessions (id INTEGER PRIMARY KEY AUTOINCREMENT, token_hash TEXT UNIQUE NOT NULL, user_id INTEGER NOT NULL, created_at DATETIME NOT NULL, expires_at DATETIME NOT NULL);
CREATE TABLE IF NOT EXISTS peers (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE NOT NULL, public_key TEXT UNIQUE NOT NULL, encrypted_private_key TEXT NOT NULL, allowed_ips TEXT NOT NULL, disabled INTEGER DEFAULT 0, last_handshake DATETIME, rx_bytes INTEGER DEFAULT 0, tx_bytes INTEGER DEFAULT 0, total_rx_bytes INTEGER DEFAULT 0, total_tx_bytes INTEGER DEFAULT 0, data_limit_gb INTEGER DEFAULT 0, expires_at INTEGER, created_at DATETIME DEFAULT CURRENT_TIMESTAMP);
CREATE TABLE IF NOT EXISTS historical_usage (id INTEGER PRIMARY KEY AUTOINCREMENT, peer_name TEXT NOT NULL, public_key TEXT, rx_bytes INTEGER DEFAULT 0, tx_bytes INTEGER DEFAULT 0, deleted_at DATETIME DEFAULT CURRENT_TIMESTAMP);
CREATE TABLE IF NOT EXISTS audit_logs (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, action TEXT NOT NULL, target TEXT, details TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP);
CREATE TABLE IF NOT EXISTS system_state (key TEXT PRIMARY KEY, value TEXT);
CREATE TABLE IF NOT EXISTS ip_pool (id INTEGER PRIMARY KEY AUTOINCREMENT, ip TEXT UNIQUE, used INTEGER DEFAULT 0);
CREATE INDEX IF NOT EXISTS idx_peers_public_key ON peers(public_key);
CREATE INDEX IF NOT EXISTS idx_sessions_token_hash ON sessions(token_hash);
SQL
chmod 600 "$DB_PATH"
log_success "Database initialized"
fi
# Auto-migrate existing databases: add new columns if missing
if [[ -f "$DB_PATH" ]]; then
# Check if data_limit_gb column exists, if not add it (and related columns)
local has_limit=$(sqlite3 "$DB_PATH" "PRAGMA table_info(peers);" | grep -c "data_limit_gb" || echo "0")
if [[ "$has_limit" == "0" ]]; then
log_info "Migrating database schema..."
sqlite3 "$DB_PATH" "ALTER TABLE peers ADD COLUMN total_rx_bytes INTEGER DEFAULT 0;" 2>/dev/null
sqlite3 "$DB_PATH" "ALTER TABLE peers ADD COLUMN total_tx_bytes INTEGER DEFAULT 0;" 2>/dev/null
sqlite3 "$DB_PATH" "ALTER TABLE peers ADD COLUMN data_limit_gb INTEGER DEFAULT 0;" 2>/dev/null
sqlite3 "$DB_PATH" "ALTER TABLE peers ADD COLUMN disabled INTEGER DEFAULT 0;" 2>/dev/null
sqlite3 "$DB_PATH" "ALTER TABLE peers ADD COLUMN expires_at INTEGER;" 2>/dev/null
log_success "Database migrated"
fi
fi
}
# Database Abstraction (Handles Standalone vs Sync mode)
db_query() {
[[ ! -f "$DB_PATH" ]] && return 1
command -v sqlite3 &>/dev/null || return 1
# Remove 2>/dev/null to allow seeing actual sqlite errors if they occur
sqlite3 -batch "$DB_PATH" "$1"
}
db_exec() {
[[ ! -f "$DB_PATH" ]] && return 0 # No-op if DB not present
command -v sqlite3 &>/dev/null || return 0
# Retry loop for locked DB (SQLITE_BUSY)
local retries=0
local max_retries=5
while [[ $retries -lt $max_retries ]]; do