-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathinstall.sh
More file actions
executable file
·2740 lines (2308 loc) · 87.5 KB
/
install.sh
File metadata and controls
executable file
·2740 lines (2308 loc) · 87.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
# ============================================================================
# Knowledge Graph Platform Installer
# ============================================================================
INSTALLER_VERSION="0.11.0"
# ============================================================================
#
# A single-command installer for the Knowledge Graph platform. Supports both
# interactive (wizard) and headless (flag-based) installation modes.
#
# ARCHITECTURE OVERVIEW:
# ----------------------
# This script follows a "configuration-first" pattern:
#
# 1. CONFIGURATION - All options defined as variables (single source of truth)
# 2. UTILITIES - Logging, prompts, validation helpers
# 3. COLLECTORS - Two paths to populate config: flags OR interactive
# 4. VALIDATORS - Verify config is complete and valid
# 5. ACTIONS - Download files, setup SSL, start containers, etc.
# 6. MAIN - Orchestrates the flow
#
# This design ensures:
# - Every headless flag has an interactive equivalent
# - Config validation works regardless of input method
# - Easy to read: want to know all options? Look at section 1
# - Easy to modify: each section is self-contained
#
# USAGE:
# ------
# Interactive: curl -fsSL .../install.sh | bash
# Headless: curl -fsSL .../install.sh | bash -s -- --hostname x --ssl y ...
# Help: curl -fsSL .../install.sh | bash -s -- --help
#
# ============================================================================
set -e # Exit on error
# ============================================================================
# SECTION 1: CONFIGURATION VARIABLES
# ============================================================================
#
# All configurable options are defined here. This is the single source of truth
# for what can be configured. Both flag parsing and interactive prompts set
# these same variables.
#
# Naming convention:
# - UPPERCASE for config that can be set by user
# - lowercase for internal/derived values
#
# --- Installation ---
INSTALL_DIR="" # Where to install (default: ~/knowledge-graph)
KG_INSTALL_DIR="$HOME/knowledge-graph" # Default install location
# --- Basic ---
HOSTNAME="" # Public hostname or IP for web access
# --- AI Provider ---
AI_PROVIDER="" # openai, anthropic, ollama, or empty to skip
AI_MODEL="" # Model name (e.g., gpt-4o, claude-sonnet-4)
AI_KEY="" # API key for cloud providers
SKIP_AI=false # Skip AI configuration entirely
# --- GPU ---
GPU_MODE="auto" # auto, nvidia, amd, cpu
# --- SSL/HTTPS ---
SSL_MODE="offload" # offload, selfsigned, letsencrypt, manual
SSL_EMAIL="" # Email for Let's Encrypt registration
SSL_CERT_PATH="" # Path to existing certificate (manual mode)
SSL_KEY_PATH="" # Path to existing private key (manual mode)
# --- SSL DNS-01 Challenge (for Let's Encrypt behind NAT/firewall) ---
SSL_DNS_PROVIDER="" # acme.sh DNS provider (e.g., dns_porkbun, dns_cloudflare)
SSL_DNS_KEY="" # DNS provider API key
SSL_DNS_SECRET="" # DNS provider API secret (if required)
SSL_USE_EXISTING_CERT=false # Reuse existing acme.sh certificate
# --- Macvlan Networking (dedicated LAN IP) ---
MACVLAN_ENABLED=false # Use macvlan networking
MACVLAN_CREATE=false # Create new kg-macvlan network
MACVLAN_DELETE=false # Delete existing kg-macvlan network
MACVLAN_NETWORK="kg-macvlan" # Network name (standard for auto-detection)
MACVLAN_PARENT="" # Parent interface (e.g., eth0, eno1)
MACVLAN_SUBNET="" # Network subnet (e.g., 192.168.1.0/24)
MACVLAN_GATEWAY="" # Gateway IP (e.g., 192.168.1.1)
MACVLAN_IP="" # Static IP for container (recommended)
MACVLAN_MAC="" # MAC address (optional, for DHCP reservation)
# --- Admin ---
ADMIN_PASSWORD="" # Admin user password (auto-generated if empty)
# --- Internal State ---
INTERACTIVE=false # Running in interactive mode
VALIDATION_ERRORS=() # Accumulated validation errors
SECRETS_GENERATED=false # Whether secrets have been generated
SAVE_CONFIG=false # Save config after installation
# --- Config File (for saving/loading user choices) ---
CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/knowledge-graph"
CONFIG_FILE="$CONFIG_DIR/install.conf"
CONFIG_VERSION="" # Version from loaded config
# --- Repository URLs ---
KG_REPO_RAW="https://raw.githubusercontent.com/aaronsb/knowledge-graph-system/main"
KG_REPO="https://github.com/aaronsb/knowledge-graph-system"
# ============================================================================
# SECTION 2: UTILITY FUNCTIONS
# ============================================================================
#
# Helper functions used throughout the script:
# - Logging (colored output)
# - User prompts (for interactive mode)
# - Validation helpers
# - System detection
#
# --- Terminal Colors ---
# Disable colors if not running in a terminal (e.g., piped to file)
if [ -t 1 ]; then
RED=$'\033[0;31m'
GREEN=$'\033[0;32m'
YELLOW=$'\033[1;33m'
BLUE=$'\033[0;34m'
CYAN=$'\033[0;36m'
BOLD=$'\033[1m'
NC=$'\033[0m' # No Color
else
RED='' GREEN='' YELLOW='' BLUE='' CYAN='' BOLD='' NC=''
fi
# --- Logging Functions ---
# These write to stderr so they display even when stdout is captured
log_info() {
echo -e "${BLUE}ℹ${NC} $1" >&2
}
log_success() {
echo -e "${GREEN}✓${NC} $1" >&2
}
log_warning() {
echo -e "${YELLOW}⚠${NC} $1" >&2
}
log_error() {
echo -e "${RED}✗${NC} $1" >&2
}
log_step() {
# Major step header
echo -e "\n${BOLD}${BLUE}==>${NC} ${BOLD}$1${NC}" >&2
}
# ============================================================================
# SUDO HELPER FUNCTIONS
# ============================================================================
# All privileged operations go through these functions, making it clear
# what requires elevated access. The sudo token is acquired once at startup.
#
# Usage:
# sudo_ensure # Acquire/refresh sudo token
# as_root mkdir -p /opt/something # Run command as root
# as_root_write "content" /opt/file # Write string to file
# as_root_write_stdin /opt/file <<EOF # Write heredoc to file
# as_root_append "line" /opt/file # Append string to file
# as_root_append_stdin /opt/file <<EOF# Append heredoc to file
# docker_cmd compose up -d # Run docker as root
# ============================================================================
sudo_ensure() {
# Acquire or refresh sudo token
# Call at startup and before privileged ops after long-running processes
# Usage: sudo_ensure
if ! sudo -v; then
log_error "Failed to acquire sudo privileges"
return 1
fi
}
as_root() {
# Run a command as root
# Usage: as_root mkdir -p /opt/dir
sudo "$@"
}
as_root_write() {
# Write content to a file as root (overwrites)
# Usage: as_root_write "content" /path/to/file
local content="$1"
local file="$2"
echo "$content" | as_root_write_stdin "$file"
}
as_root_write_stdin() {
# Write stdin to a file as root (for heredocs)
# Usage: as_root_write_stdin /path/to/file <<< "content"
# or: as_root_write_stdin /path/to/file < somefile
local file="$1"
sudo tee "$file" > /dev/null
}
as_root_append() {
# Append content to a file as root
# Usage: as_root_append "line" /path/to/file
local content="$1"
local file="$2"
echo "$content" | sudo tee -a "$file" > /dev/null
}
as_root_append_stdin() {
# Append stdin to a file as root (for heredocs)
# Usage: as_root_append_stdin /path/to/file << 'EOF'
local file="$1"
sudo tee -a "$file" > /dev/null
}
docker_cmd() {
# Run docker command (always needs sudo unless user is in docker group)
# Usage: docker_cmd compose up -d
sudo docker "$@"
}
# --- Prompt Functions ---
# These handle user input in interactive mode. All read from /dev/tty
# to work correctly when script is piped (curl | bash).
prompt_value() {
# Prompt for a text value with optional default
# Usage: result=$(prompt_value "Prompt text" "default")
local prompt="$1"
local default="$2"
local value
if [[ -n "$default" ]]; then
echo -ne "${CYAN}?${NC} ${prompt} [${default}]: " >&2
read -r value </dev/tty
echo "${value:-$default}"
else
echo -ne "${CYAN}?${NC} ${prompt}: " >&2
read -r value </dev/tty
echo "$value"
fi
}
prompt_password() {
# Prompt for a password (hidden input)
# Usage: result=$(prompt_password "Password")
local prompt="$1"
local value
echo -ne "${CYAN}?${NC} ${prompt}: " >&2
read -sr value </dev/tty
echo >&2 # Newline after hidden input
echo "$value"
}
prompt_password_confirm() {
# Prompt for a password with confirmation
# Usage: result=$(prompt_password_confirm "Password")
local prompt="$1"
local value1 value2
while true; do
echo -ne "${CYAN}?${NC} ${prompt}: " >&2
read -sr value1 </dev/tty
echo >&2
echo -ne "${CYAN}?${NC} Confirm ${prompt,,}: " >&2
read -sr value2 </dev/tty
echo >&2
if [[ "$value1" == "$value2" ]]; then
echo "$value1"
return 0
else
log_warning "Passwords don't match, try again"
fi
done
}
prompt_select() {
# Prompt user to select from a list of options
# Usage: result=$(prompt_select "Question" "opt1" "opt2" "opt3")
# Returns the selected option text
local prompt="$1"
shift
local options=("$@")
echo -e "${CYAN}?${NC} ${prompt}" >&2
local i=1
for opt in "${options[@]}"; do
echo " ${i}) ${opt}" >&2
((i++))
done
local selection
echo -ne " Choice [1]: " >&2
read -r selection </dev/tty
selection=${selection:-1}
if [[ "$selection" -ge 1 && "$selection" -le ${#options[@]} ]]; then
echo "${options[$((selection-1))]}"
else
echo "${options[0]}" # Default to first option
fi
}
prompt_bool() {
# Prompt for yes/no answer
# Usage: if prompt_bool "Enable feature?"; then ...
local prompt="$1"
local default="${2:-n}" # Default to 'n' if not specified
local response
if [[ "$default" == "y" ]]; then
echo -ne "${CYAN}?${NC} ${prompt} [Y/n]: " >&2
else
echo -ne "${CYAN}?${NC} ${prompt} [y/N]: " >&2
fi
read -r response </dev/tty
response="${response:-$default}"
[[ "$response" =~ ^[Yy] ]]
}
prompt_with_fallback() {
# Three-tier prompt: previous config → auto-detect → custom entry
# Usage: result=$(prompt_with_fallback "Prompt text" "$PREVIOUS_VAR" "$auto_detected")
#
# Behavior:
# - If previous exists: shows "Previous: value" and uses it as default
# - If no previous: uses auto-detected as default
# - User presses Enter to accept shown default, or types to override
local prompt="$1"
local previous="$2"
local detected="$3"
local default=""
local hint=""
if [[ -n "$previous" ]]; then
default="$previous"
hint="${GRAY}(previous)${NC}"
elif [[ -n "$detected" ]]; then
default="$detected"
hint="${GRAY}(detected)${NC}"
fi
if [[ -n "$default" ]]; then
echo -ne "${CYAN}?${NC} ${prompt} ${hint}\n [${default}]: " >&2
else
echo -ne "${CYAN}?${NC} ${prompt}: " >&2
fi
local value
read -r value </dev/tty
echo "${value:-$default}"
}
# --- Validation Helpers ---
add_validation_error() {
# Add an error to the validation error list
VALIDATION_ERRORS+=("$1")
}
validate_ip() {
# Check if string is a valid IPv4 address
local ip="$1"
[[ "$ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]
}
validate_cidr() {
# Check if string is a valid CIDR notation
local cidr="$1"
[[ "$cidr" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/[0-9]+$ ]]
}
validate_hostname_format() {
# Check if string looks like a valid hostname or IP
local host="$1"
[[ -n "$host" ]] && [[ "$host" =~ ^[a-zA-Z0-9]([a-zA-Z0-9\.\-]*[a-zA-Z0-9])?$ || "$host" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]
}
validate_email() {
# Basic email format validation
local email="$1"
[[ "$email" =~ ^[^@]+@[^@]+\.[^@]+$ ]]
}
# --- System Detection ---
detect_default_interface() {
# Find the default network interface
ip route | grep default | awk '{print $5}' | head -1
}
detect_default_ip() {
# Get the first non-localhost IP
hostname -I 2>/dev/null | awk '{print $1}'
}
is_private_ip() {
# Check if hostname/IP is private (would need DNS-01 for Let's Encrypt)
local host="$1"
[[ "$host" == "localhost" ]] || \
[[ "$host" =~ ^192\.168\. ]] || \
[[ "$host" =~ ^10\. ]] || \
[[ "$host" =~ ^172\.(1[6-9]|2[0-9]|3[01])\. ]] || \
[[ "$host" =~ \.local$ ]] || \
[[ "$host" =~ \.internal$ ]]
}
# --- Certificate Checking ---
check_existing_acme_cert() {
# Check for existing acme.sh certificate for a domain
# Returns 0 if valid cert exists, 1 otherwise
# Usage: if check_existing_acme_cert "example.com"; then ...
local domain="$1"
local acme_home="${ACME_HOME:-$HOME/.acme.sh}"
local cert_dir="$acme_home/$domain"
local cert_file="$cert_dir/$domain.cer"
# Check if cert exists
if [[ ! -f "$cert_file" ]]; then
return 1
fi
# Check if cert is valid (not expired)
local expiry_epoch
expiry_epoch=$(openssl x509 -in "$cert_file" -noout -enddate 2>/dev/null | cut -d= -f2)
if [[ -z "$expiry_epoch" ]]; then
return 1
fi
local expiry_ts
expiry_ts=$(date -d "$expiry_epoch" +%s 2>/dev/null)
local now_ts
now_ts=$(date +%s)
# Check if cert expires in more than 7 days
local min_remaining=$((7 * 24 * 60 * 60))
if [[ $((expiry_ts - now_ts)) -lt $min_remaining ]]; then
return 1
fi
return 0
}
show_cert_info() {
# Display certificate info for user
# Usage: show_cert_info "example.com"
local domain="$1"
local acme_home="${ACME_HOME:-$HOME/.acme.sh}"
local cert_file="$acme_home/$domain/$domain.cer"
if [[ ! -f "$cert_file" ]]; then
return 1
fi
local subject issuer expiry
subject=$(openssl x509 -in "$cert_file" -noout -subject 2>/dev/null | sed 's/subject=//')
issuer=$(openssl x509 -in "$cert_file" -noout -issuer 2>/dev/null | sed 's/issuer=//' | sed 's/.*O = //' | cut -d',' -f1)
expiry=$(openssl x509 -in "$cert_file" -noout -enddate 2>/dev/null | cut -d= -f2)
echo -e " ${BOLD}Domain:${NC} $domain"
echo -e " ${BOLD}Issuer:${NC} $issuer"
echo -e " ${BOLD}Expires:${NC} $expiry"
}
# --- API Key Validation ---
validate_openai_key() {
# Validate OpenAI API key by hitting the models endpoint
# Returns 0 if valid, 1 if invalid
# Usage: if validate_openai_key "$key"; then ...
local api_key="$1"
if [[ -z "$api_key" ]]; then
return 1
fi
local response
response=$(curl -sf -w "%{http_code}" -o /dev/null \
-H "Authorization: Bearer $api_key" \
"https://api.openai.com/v1/models" 2>/dev/null)
[[ "$response" == "200" ]]
}
list_openai_models() {
# List available OpenAI models for chat/completion
# Returns newline-separated list of model IDs
# Usage: models=$(list_openai_models "$key")
local api_key="$1"
curl -sf -H "Authorization: Bearer $api_key" \
"https://api.openai.com/v1/models" 2>/dev/null | \
grep -o '"id":"[^"]*"' | \
sed 's/"id":"//g; s/"//g' | \
grep -E '^gpt-' | \
sort -r | \
head -10
}
validate_anthropic_key() {
# Validate Anthropic API key
# Returns 0 if valid, 1 if invalid
local api_key="$1"
if [[ -z "$api_key" ]]; then
return 1
fi
# Anthropic doesn't have a simple models list endpoint
# Use a minimal message request that will fail but tell us if key is valid
local response
response=$(curl -sf -w "%{http_code}" -o /dev/null \
-H "x-api-key: $api_key" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{"model":"claude-3-haiku-20240307","max_tokens":1,"messages":[{"role":"user","content":"hi"}]}' \
"https://api.anthropic.com/v1/messages" 2>/dev/null)
# 200 = valid request, 400 = valid key but bad request, 401 = invalid key
[[ "$response" == "200" || "$response" == "400" ]]
}
prompt_api_key_with_validation() {
# Prompt for API key with retry on failure
# Usage: key=$(prompt_api_key_with_validation "openai")
local provider="$1"
local key=""
local max_attempts=3
local attempt=1
while [[ $attempt -le $max_attempts ]]; do
key=$(prompt_value "${provider^} API key" "")
if [[ -z "$key" ]]; then
log_warning "API key is required"
return 1
fi
echo -ne " Validating API key... " >&2
local valid=false
case "$provider" in
openai)
if validate_openai_key "$key"; then
valid=true
fi
;;
anthropic)
if validate_anthropic_key "$key"; then
valid=true
fi
;;
*)
# Unknown provider - skip validation
valid=true
;;
esac
if [[ "$valid" == "true" ]]; then
echo -e "${GREEN}✓ Valid${NC}" >&2
echo "$key"
return 0
else
echo -e "${RED}✗ Invalid${NC}" >&2
if [[ $attempt -lt $max_attempts ]]; then
log_warning "Invalid API key. Please try again ($attempt/$max_attempts)"
((attempt++))
else
log_error "Failed to validate API key after $max_attempts attempts"
return 1
fi
fi
done
return 1
}
# --- Config File Management ---
# Save/load user choices for round-tripping between interactive and headless modes.
# Similar to acme.sh, the config is stored in user profile (not root-owned).
get_installer_version() {
echo "$INSTALLER_VERSION"
}
save_config() {
# Save current configuration to config file
# Usage: save_config
local version
version=$(get_installer_version)
mkdir -p "$CONFIG_DIR"
chmod 700 "$CONFIG_DIR"
cat > "$CONFIG_FILE" << EOF
# Knowledge Graph Installer Configuration
# Generated by install.sh $version on $(date -Iseconds)
# This file can be used with: ./install.sh --config "$CONFIG_FILE"
INSTALLER_VERSION="0.11.0"
# --- Installation ---
INSTALL_DIR="$INSTALL_DIR"
HOSTNAME="$HOSTNAME"
# --- AI Provider ---
AI_PROVIDER="$AI_PROVIDER"
AI_MODEL="$AI_MODEL"
# Note: API keys are NOT saved for security - enter during install
# --- GPU ---
GPU_MODE="$GPU_MODE"
# --- SSL/HTTPS ---
SSL_MODE="$SSL_MODE"
SSL_EMAIL="$SSL_EMAIL"
SSL_DNS_PROVIDER="$SSL_DNS_PROVIDER"
# Note: DNS secrets are NOT saved for security
# --- Macvlan Networking ---
MACVLAN_ENABLED="$MACVLAN_ENABLED"
MACVLAN_PARENT="$MACVLAN_PARENT"
MACVLAN_SUBNET="$MACVLAN_SUBNET"
MACVLAN_GATEWAY="$MACVLAN_GATEWAY"
MACVLAN_IP="$MACVLAN_IP"
EOF
chmod 600 "$CONFIG_FILE"
log_info "Configuration saved to $CONFIG_FILE"
}
load_config() {
# Load configuration from config file
# Usage: load_config "/path/to/config"
# Returns 0 if loaded, 1 if file not found or invalid
local config_path="${1:-$CONFIG_FILE}"
if [[ ! -f "$config_path" ]]; then
return 1
fi
# Source the config file (it's shell variables)
# shellcheck disable=SC1090
source "$config_path"
# Store the version from config for compatibility check
CONFIG_VERSION="${INSTALLER_VERSION:-unknown}"
return 0
}
check_config_compatibility() {
# Check if loaded config is compatible with current installer
# Returns 0 if compatible, 1 if not
local current_version
current_version=$(get_installer_version)
if [[ -z "$CONFIG_VERSION" ]]; then
return 1
fi
# Extract major.minor from versions (ignore patch/dev)
local current_major_minor config_major_minor
current_major_minor=$(echo "$current_version" | grep -oE '^[0-9]+\.[0-9]+')
config_major_minor=$(echo "$CONFIG_VERSION" | grep -oE '^[0-9]+\.[0-9]+')
[[ "$current_major_minor" == "$config_major_minor" ]]
}
show_config_summary() {
# Display loaded config for user confirmation
echo -e "${BOLD}Previous configuration found:${NC}"
echo -e " ${BOLD}Version:${NC} $CONFIG_VERSION"
echo -e " ${BOLD}Hostname:${NC} ${HOSTNAME:-not set}"
echo -e " ${BOLD}SSL Mode:${NC} ${SSL_MODE:-offload}"
[[ -n "$AI_PROVIDER" ]] && echo -e " ${BOLD}AI:${NC} $AI_PROVIDER ($AI_MODEL)"
[[ "$MACVLAN_ENABLED" == "true" ]] && echo -e " ${BOLD}Macvlan:${NC} $MACVLAN_IP"
echo
}
# ============================================================================
# SECTION 3A: FLAG PARSING (Headless Mode)
# ============================================================================
#
# Parse command-line flags to populate configuration variables.
# Every flag here should have a corresponding interactive prompt in Section 3B.
#
show_help() {
cat << 'EOF'
Knowledge Graph Platform Installer
Install the Knowledge Graph system on a fresh server.
USAGE:
curl -fsSL <url>/install.sh | bash # Interactive mode
curl -fsSL <url>/install.sh | bash -s -- [OPTIONS] # Headless mode
BASIC OPTIONS:
--hostname HOSTNAME Public hostname or IP for web access
--install-dir DIR Installation directory (default: ~/knowledge-graph)
--config FILE Load configuration from file (enables headless mode)
--save-config Save configuration to ~/.config/knowledge-graph/install.conf
--help Show this help message
AI PROVIDER OPTIONS:
--ai-provider PROVIDER AI extraction provider: openai, anthropic, ollama
--ai-model MODEL Model name (default varies by provider)
--ai-key KEY API key for the AI provider
--skip-ai Skip AI provider configuration (configure later)
GPU OPTIONS:
--gpu MODE GPU acceleration: auto, nvidia, amd, cpu (default: auto)
SSL/HTTPS OPTIONS:
--ssl MODE SSL mode: offload, selfsigned, letsencrypt, manual
• offload: HTTP only (behind reverse proxy)
• selfsigned: Generate self-signed cert
• letsencrypt: Auto-generate via Let's Encrypt
• manual: Use existing certificates
--ssl-email EMAIL Email for Let's Encrypt registration
--ssl-cert PATH Path to SSL certificate (manual mode)
--ssl-key PATH Path to SSL private key (manual mode)
--ssl-dns PROVIDER DNS provider for DNS-01 challenge (e.g., dns_porkbun)
Required for Let's Encrypt on private networks
--ssl-dns-key KEY DNS provider API key
--ssl-dns-secret SECRET DNS provider API secret
MACVLAN OPTIONS (Dedicated LAN IP):
--macvlan Use existing kg-macvlan network
--macvlan-ip IP Static IP on macvlan (recommended)
--macvlan-mac MAC MAC address for DHCP reservation
--macvlan-create Create new kg-macvlan network
--macvlan-parent IFACE Parent interface (e.g., eth0, eno1)
--macvlan-subnet CIDR Network subnet (e.g., 192.168.1.0/24)
--macvlan-gateway IP Gateway IP (e.g., 192.168.1.1)
--macvlan-delete Delete existing kg-macvlan network
ADMIN OPTIONS:
--admin-password PASS Set admin password (default: auto-generated)
EXAMPLES:
# Interactive installation
curl -fsSL https://raw.githubusercontent.com/.../install.sh | bash
# Basic headless with OpenAI
curl -fsSL .../install.sh | bash -s -- \
--hostname myserver.example.com \
--ai-provider openai --ai-key "$OPENAI_API_KEY"
# Let's Encrypt with DNS-01 (Porkbun) + macvlan
curl -fsSL .../install.sh | bash -s -- \
--hostname kg.example.com \
--ssl letsencrypt --ssl-email admin@example.com \
--ssl-dns dns_porkbun \
--ssl-dns-key "$PORKBUN_API_KEY" \
--ssl-dns-secret "$PORKBUN_SECRET_KEY" \
--macvlan --macvlan-ip 192.168.1.82 \
--skip-ai
EOF
exit 0
}
parse_flags() {
# Parse command-line arguments and set configuration variables
#
# If no flags are provided (or only unknown flags), we'll run in
# interactive mode. If ANY known flag is provided, we're in headless mode.
local has_known_flags=false
while [[ $# -gt 0 ]]; do
case "$1" in
# --- Help ---
--help|-h)
show_help
;;
# --- Installation ---
--install-dir)
INSTALL_DIR="$2"
has_known_flags=true
shift 2
;;
# --- Config File ---
--config)
if ! load_config "$2"; then
echo -e "${RED}Failed to load config: $2${NC}"
exit 1
fi
if ! check_config_compatibility; then
echo -e "${YELLOW}Warning: Config from different version ($CONFIG_VERSION)${NC}"
fi
has_known_flags=true
shift 2
;;
--save-config)
SAVE_CONFIG=true
shift
;;
# --- Basic ---
--hostname)
HOSTNAME="$2"
has_known_flags=true
shift 2
;;
# --- AI Provider ---
--ai-provider)
AI_PROVIDER="$2"
has_known_flags=true
shift 2
;;
--ai-model)
AI_MODEL="$2"
has_known_flags=true
shift 2
;;
--ai-key)
AI_KEY="$2"
has_known_flags=true
shift 2
;;
--skip-ai)
SKIP_AI=true
has_known_flags=true
shift
;;
# --- GPU ---
--gpu)
GPU_MODE="$2"
has_known_flags=true
shift 2
;;
# --- SSL ---
--ssl)
SSL_MODE="$2"
has_known_flags=true
shift 2
;;
--ssl-email)
SSL_EMAIL="$2"
has_known_flags=true
shift 2
;;
--ssl-cert)
SSL_CERT_PATH="$2"
has_known_flags=true
shift 2
;;
--ssl-key)
SSL_KEY_PATH="$2"
has_known_flags=true
shift 2
;;
--ssl-dns)
SSL_DNS_PROVIDER="$2"
has_known_flags=true
shift 2
;;
--ssl-dns-key)
SSL_DNS_KEY="$2"
has_known_flags=true
shift 2
;;
--ssl-dns-secret)
SSL_DNS_SECRET="$2"
has_known_flags=true
shift 2
;;
# --- Macvlan ---
--macvlan)
MACVLAN_ENABLED=true
has_known_flags=true
shift
;;
--macvlan-create)
MACVLAN_ENABLED=true
MACVLAN_CREATE=true
has_known_flags=true
shift
;;
--macvlan-delete)
MACVLAN_DELETE=true
has_known_flags=true
shift
;;
--macvlan-parent)
MACVLAN_PARENT="$2"
has_known_flags=true
shift 2
;;
--macvlan-subnet)
MACVLAN_SUBNET="$2"
has_known_flags=true
shift 2
;;
--macvlan-gateway)
MACVLAN_GATEWAY="$2"
has_known_flags=true
shift 2
;;
--macvlan-ip)
MACVLAN_IP="$2"
has_known_flags=true
shift 2
;;
--macvlan-mac)
MACVLAN_MAC="$2"
has_known_flags=true
shift 2
;;
# --- Admin ---
--admin-password)
ADMIN_PASSWORD="$2"
has_known_flags=true
shift 2
;;
# --- Unknown ---
*)
log_error "Unknown option: $1"
log_info "Run with --help for usage information"
exit 1
;;
esac
done
# If no known flags were provided, run in interactive mode
if [[ "$has_known_flags" == "false" ]]; then
INTERACTIVE=true
fi
}
# ============================================================================
# SECTION 3B: INTERACTIVE PROMPTS (Wizard Mode)
# ============================================================================
#
# Step-based interactive setup. Each step handles one category of config
# and mirrors the flags available in headless mode.
#
# Steps are run in order by run_interactive_setup(). Each step:
# 1. Displays a header
# 2. Prompts for relevant options
# 3. Sets the corresponding config variables
#
step_welcome() {
# Display welcome message and explain what will happen
echo
echo -e "${BOLD}${BLUE}Knowledge Graph Platform Installer${NC}"
echo
echo "This wizard will guide you through the installation."
echo "You can also run with --help to see headless options."
echo
}
step_install_dir() {
# Step: Choose installation directory
echo
echo -e "${BOLD}=== Installation Location ===${NC}"
echo
local previous_dir="$INSTALL_DIR"
INSTALL_DIR=$(prompt_with_fallback "Installation directory" "$previous_dir" "$KG_INSTALL_DIR")
}
step_hostname() {
# Step: Configure hostname/IP for web access
echo
echo -e "${BOLD}=== Basic Configuration ===${NC}"
echo
local detected_host
detected_host=$(detect_default_ip)