-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinstall.sh
More file actions
1989 lines (1619 loc) · 59.7 KB
/
install.sh
File metadata and controls
1989 lines (1619 loc) · 59.7 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
# IPFS Pinning Service Installation Script
# This script installs or upgrades the IPFS Pinning Service with SQLite backend
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Default values
DEFAULT_TARGET_DIR="/home/root/pinning-service"
DEFAULT_PORT="6000"
DEFAULT_IPFS_API_ADDR="/ip4/127.0.0.1/tcp/5001"
DEFAULT_IPFS_CLUSTER_API_ADDR="/ip4/127.0.0.1/tcp/9094"
DEFAULT_ENABLE_IPFS_PINNING="false"
DEFAULT_DB_PATH="data/pinning.db"
# Pinning service
SERVICE_NAME="fula-pinning-service"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
# IPFS Gateway/Upload server
GATEWAY_SERVICE_NAME="fula-upload-server"
GATEWAY_SERVICE_FILE="/etc/systemd/system/${GATEWAY_SERVICE_NAME}.service"
DEFAULT_GATEWAY_PORT="3300"
# WebUI server
WEBUI_SERVICE_NAME="fula-pinning-webui"
WEBUI_SERVICE_FILE="/etc/systemd/system/${WEBUI_SERVICE_NAME}.service"
DEFAULT_WEBUI_PORT="3001"
# Nginx configuration
NGINX_AVAILABLE="/etc/nginx/sites-available"
NGINX_ENABLED="/etc/nginx/sites-enabled"
# Print colored message
print_msg() {
local color=$1
local msg=$2
echo -e "${color}${msg}${NC}"
}
print_info() { print_msg "$BLUE" "[INFO] $1"; }
print_success() { print_msg "$GREEN" "[SUCCESS] $1"; }
print_warning() { print_msg "$YELLOW" "[WARNING] $1"; }
print_error() { print_msg "$RED" "[ERROR] $1"; }
# Check if running as root
check_root() {
if [ "$EUID" -ne 0 ]; then
print_error "Please run as root (use sudo)"
exit 1
fi
}
# Verify a step completed successfully
verify_step() {
local step_name=$1
local check_cmd=$2
if eval "$check_cmd"; then
print_success "$step_name completed successfully"
return 0
else
print_error "$step_name failed"
return 1
fi
}
# Source nvm if available (for correct Node.js version)
setup_node_env() {
# Try to source nvm from common locations
export NVM_DIR="${NVM_DIR:-$HOME/.nvm}"
if [ -s "$NVM_DIR/nvm.sh" ]; then
source "$NVM_DIR/nvm.sh"
print_info "Using nvm Node.js: $(node -v)"
elif [ -s "/root/.nvm/nvm.sh" ]; then
export NVM_DIR="/root/.nvm"
source "$NVM_DIR/nvm.sh"
print_info "Using nvm Node.js: $(node -v)"
elif [ -s "$HOME/.nvm/nvm.sh" ]; then
export NVM_DIR="$HOME/.nvm"
source "$NVM_DIR/nvm.sh"
print_info "Using nvm Node.js: $(node -v)"
fi
}
# Load existing .env files from all services if they exist
load_existing_env() {
local target_dir="$1"
# Load pinning service env
if [ -f "$target_dir/.env" ]; then
print_info "Found existing pinning service .env file, loading defaults..."
source "$target_dir/.env" 2>/dev/null || true
fi
# Load ipfs-server env
if [ -f "$target_dir/ipfs-server/.env" ]; then
print_info "Found existing ipfs-server .env file, loading defaults..."
source "$target_dir/ipfs-server/.env" 2>/dev/null || true
fi
# Load webui env
if [ -f "$target_dir/pinning-webui/.env" ]; then
print_info "Found existing webui .env file, loading defaults..."
source "$target_dir/pinning-webui/.env" 2>/dev/null || true
fi
# Sanitize DATABASE_PATH - fix duplicated paths
if [ -n "$DATABASE_PATH" ]; then
# If path contains duplicated target_dir, extract just the relative part
if [[ "$DATABASE_PATH" == *"$target_dir"*"$target_dir"* ]]; then
print_warning "Detected corrupted DATABASE_PATH, fixing..."
DATABASE_PATH="data/pinning.db"
# If it's already an absolute path, convert to relative
elif [[ "$DATABASE_PATH" == /* ]]; then
# Extract just the relative path after target_dir
DATABASE_PATH="${DATABASE_PATH##$target_dir/}"
# If still absolute, use default
if [[ "$DATABASE_PATH" == /* ]]; then
DATABASE_PATH="data/pinning.db"
fi
fi
fi
}
# Prompt for configuration value with default
prompt_value() {
local prompt=$1
local default=$2
local var_name=$3
local is_secret=${4:-false}
if [ "$is_secret" = true ]; then
read -sp "$prompt [$default]: " value
echo
else
read -p "$prompt [$default]: " value
fi
if [ -z "$value" ]; then
value="$default"
fi
eval "$var_name='$value'"
}
# Check if directory is empty (excluding hidden files)
is_dir_empty() {
local dir=$1
if [ -d "$dir" ]; then
if [ -z "$(ls -A "$dir" 2>/dev/null)" ]; then
return 0
fi
fi
return 1
}
# Detect installation type
detect_install_type() {
local target_dir=$1
if [ ! -d "$target_dir" ]; then
echo "fresh"
elif is_dir_empty "$target_dir"; then
echo "fresh"
elif [ -f "$target_dir/ipfs-pinning" ]; then
echo "upgrade"
else
echo "fresh"
fi
}
# Stop existing service if running
stop_service() {
if systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
print_info "Stopping existing pinning service..."
systemctl stop "$SERVICE_NAME"
sleep 2
fi
}
# Stop existing gateway service if running
stop_gateway_service() {
if systemctl is-active --quiet "$GATEWAY_SERVICE_NAME" 2>/dev/null; then
print_info "Stopping existing gateway service..."
systemctl stop "$GATEWAY_SERVICE_NAME"
sleep 2
fi
}
# Stop existing webui service if running
stop_webui_service() {
if systemctl is-active --quiet "$WEBUI_SERVICE_NAME" 2>/dev/null; then
print_info "Stopping existing WebUI service..."
systemctl stop "$WEBUI_SERVICE_NAME"
sleep 2
fi
}
# Build the application
build_app() {
local source_dir=$1
local target_dir=$2
print_info "Building pinning service..."
cd "$source_dir"
# Download dependencies
go mod download
# Build with SQLite backend
go build -o "$target_dir/ipfs-pinning" -tags "sqlite" main_sqlite.go
verify_step "Pinning service build" "[ -f '$target_dir/ipfs-pinning' ]"
}
# Build the IPFS gateway server
build_gateway() {
local source_dir=$1
local target_dir=$2
print_info "Building IPFS gateway server..."
# Check if Node.js is installed
if ! command -v node &> /dev/null; then
print_warning "Node.js not found. Skipping gateway build."
print_info "Install Node.js 18+ and run: cd $target_dir/ipfs-server && npm install && npm run build"
return 1
fi
# Check Node.js version
NODE_VERSION=$(node -v | cut -d'v' -f2 | cut -d'.' -f1)
if [ "$NODE_VERSION" -lt 18 ]; then
print_warning "Node.js 18+ required. Found: $(node -v). Skipping gateway build."
return 1
fi
cd "$source_dir/ipfs-server"
# Install dependencies
print_info "Installing Node.js dependencies..."
npm install --production=false
# Build the application
print_info "Building gateway server..."
npm run build
# Copy built files to target
mkdir -p "$target_dir/ipfs-server/dist"
mkdir -p "$target_dir/ipfs-server/uploads"
cp -r dist/* "$target_dir/ipfs-server/dist/"
# Copy package files for production dependencies
cp package.json "$target_dir/ipfs-server/"
cp package-lock.json "$target_dir/ipfs-server/" 2>/dev/null || true
# Install production dependencies in target directory (for native modules like better-sqlite3)
print_info "Installing production dependencies in target directory..."
cd "$target_dir/ipfs-server"
npm install --production --ignore-scripts=false
verify_step "Gateway build" "[ -f '$target_dir/ipfs-server/dist/index.js' ] || [ -f '$target_dir/ipfs-server/dist/ipfs-gateway' ]"
}
# Build the WebUI
build_webui() {
local source_dir=$1
local target_dir=$2
print_info "Building Pinning WebUI..."
# Check if Node.js is installed
if ! command -v node &> /dev/null; then
print_warning "Node.js not found. Skipping WebUI build."
return 1
fi
# Check Node.js version
NODE_VERSION=$(node -v | cut -d'v' -f2 | cut -d'.' -f1)
if [ "$NODE_VERSION" -lt 18 ]; then
print_warning "Node.js 18+ required. Found: $(node -v). Skipping WebUI build."
return 1
fi
cd "$source_dir/pinning-webui"
# Install dependencies
print_info "Installing WebUI dependencies..."
npm install
# Build the application
# VITE_GOOGLE_CLIENT_ID must be set at build time for Vite to embed it
print_info "Building WebUI..."
if [ -n "$GOOGLE_CLIENT_ID" ]; then
VITE_GOOGLE_CLIENT_ID="$GOOGLE_CLIENT_ID" npm run build
else
npm run build
fi
# Copy built files to target
mkdir -p "$target_dir/pinning-webui/dist"
cp -r dist/* "$target_dir/pinning-webui/dist/"
# Copy package files for production dependencies
cp package.json "$target_dir/pinning-webui/"
cp package-lock.json "$target_dir/pinning-webui/" 2>/dev/null || true
# Install production dependencies in target directory (for native modules like better-sqlite3)
print_info "Installing production dependencies in target directory..."
cd "$target_dir/pinning-webui"
npm install --production --ignore-scripts=false
# Rebuild native modules with current Node version
print_info "Rebuilding native modules for Node $(node -v)..."
npm rebuild
verify_step "WebUI build" "[ -d '$target_dir/pinning-webui/dist/public' ]"
}
# Create directory structure
create_directories() {
local target_dir=$1
print_info "Creating directory structure..."
mkdir -p "$target_dir"
mkdir -p "$target_dir/data"
mkdir -p "$target_dir/logs"
mkdir -p "$target_dir/ipfs-server/dist"
mkdir -p "$target_dir/ipfs-server/uploads"
mkdir -p "$target_dir/ipfs-server/.well-known/acme-challenge"
mkdir -p "$target_dir/pinning-webui/dist"
verify_step "Directory creation" "[ -d '$target_dir/data' ] && [ -d '$target_dir/ipfs-server' ]"
}
# Generate .env file
generate_env_file() {
local target_dir=$1
print_info "Generating .env file..."
cat > "$target_dir/.env" << EOF
# IPFS Pinning Service Configuration
# Generated on $(date)
# Server Configuration
PORT=${PORT}
# Database Configuration (SQLite)
DATABASE_PATH=${DATABASE_PATH}
# IPFS Configuration
IPFS_API_ADDR=${IPFS_API_ADDR}
IPFS_CLUSTER_API_ADDR=${IPFS_CLUSTER_API_ADDR}
ENABLE_IPFS_PINNING=${ENABLE_IPFS_PINNING}
# Domain Configuration (for nginx/SSL)
PINNING_DOMAIN=${PINNING_DOMAIN}
SSL_EMAIL=${SSL_EMAIL}
# Admin API (optional - set to enable admin endpoints)
# SYSTEM_KEY=your-secret-admin-key
EOF
chmod 600 "$target_dir/.env"
verify_step ".env file creation" "[ -f '$target_dir/.env' ]"
}
# Create systemd service file
create_service_file() {
local target_dir=$1
print_info "Creating systemd service file..."
cat > "$SERVICE_FILE" << EOF
[Unit]
Description=IPFS Pinning Service (SQLite Backend)
After=network.target ipfs.service
Wants=network-online.target
[Service]
Type=simple
ExecStart=${target_dir}/ipfs-pinning
Restart=on-failure
RestartSec=10
User=root
WorkingDirectory=${target_dir}
Environment=PATH=/usr/bin:/usr/local/bin
EnvironmentFile=${target_dir}/.env
# Security hardening
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=false
ReadWritePaths=${target_dir}/data ${target_dir}/logs
# Resource limits
LimitNOFILE=65535
MemoryMax=1G
# Logging
StandardOutput=journal
StandardError=journal
SyslogIdentifier=${SERVICE_NAME}
[Install]
WantedBy=multi-user.target
EOF
chmod 644 "$SERVICE_FILE"
verify_step "Service file creation" "[ -f '$SERVICE_FILE' ]"
}
# Generate gateway .env file
generate_gateway_env_file() {
local target_dir=$1
print_info "Generating gateway .env file..."
cat > "$target_dir/ipfs-server/.env" << EOF
# IPFS Gateway Server Configuration
# Generated on $(date)
# Server Configuration
GATEWAY_PORT=${GATEWAY_PORT}
# Database Configuration (read-only access to pinning service DB)
# Use absolute path if DATABASE_PATH starts with /, otherwise relative to target_dir
DATABASE_PATH=$(if [[ "${DATABASE_PATH}" == /* ]]; then echo "${DATABASE_PATH}"; else echo "${target_dir}/${DATABASE_PATH}"; fi)
# IPFS Configuration
IPFS_API_URL=http://127.0.0.1:5001
# Upload Configuration
UPLOAD_DIR=${target_dir}/ipfs-server/uploads
MAX_FILE_SIZE=838860800
IPFS_TIMEOUT=60000
# Domain Configuration (for nginx/SSL)
IPFS_SERVER_DOMAIN=${IPFS_SERVER_DOMAIN}
EOF
chmod 600 "$target_dir/ipfs-server/.env"
verify_step "Gateway .env file creation" "[ -f '$target_dir/ipfs-server/.env' ]"
}
# Create gateway systemd service file
create_gateway_service_file() {
local target_dir=$1
print_info "Creating gateway systemd service file..."
cat > "$GATEWAY_SERVICE_FILE" << EOF
[Unit]
Description=IPFS Gateway and Upload Server
Documentation=https://github.com/functionland/pinning-service
After=network.target ipfs.service fula-pinning-service.service
Wants=network-online.target
StartLimitBurst=5
StartLimitIntervalSec=60
[Service]
Type=simple
ExecStart=${target_dir}/ipfs-server/dist/ipfs-gateway
Restart=on-failure
RestartSec=10
User=root
WorkingDirectory=${target_dir}/ipfs-server
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
EnvironmentFile=${target_dir}/ipfs-server/.env
# Security hardening
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=false
ReadWritePaths=${target_dir}/ipfs-server/uploads ${target_dir}/data
# Resource limits
LimitNOFILE=65535
MemoryMax=2G
# Logging
StandardOutput=journal
StandardError=journal
SyslogIdentifier=fula-upload-server
[Install]
WantedBy=multi-user.target
EOF
chmod 644 "$GATEWAY_SERVICE_FILE"
verify_step "Gateway service file creation" "[ -f '$GATEWAY_SERVICE_FILE' ]"
}
# Generate WebUI .env file
generate_webui_env_file() {
local target_dir=$1
print_info "Generating WebUI .env file..."
# Generate a random session secret
SESSION_SECRET=$(openssl rand -hex 32 2>/dev/null || cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 64 | head -n 1)
cat > "$target_dir/pinning-webui/.env" << EOF
# FULA Pinning WebUI Configuration
# Generated on $(date)
# Server port
WEBUI_PORT=${WEBUI_PORT}
# Node environment
NODE_ENV=production
# Database path (same as pinning service)
# Use absolute path if DATABASE_PATH starts with /, otherwise relative to target_dir
DATABASE_PATH=$(if [[ "${DATABASE_PATH}" == /* ]]; then echo "${DATABASE_PATH}"; else echo "${target_dir}/${DATABASE_PATH}"; fi)
# Google OAuth Client ID
# Get this from: https://console.cloud.google.com/apis/credentials
# Both variables use the same value - backend needs GOOGLE_CLIENT_ID, frontend needs VITE_ prefix
GOOGLE_CLIENT_ID=${GOOGLE_CLIENT_ID}
VITE_GOOGLE_CLIENT_ID=${GOOGLE_CLIENT_ID}
# Session secret (auto-generated)
SESSION_SECRET=${SESSION_SECRET}
# Pinning service URL
PINNING_SERVICE_URL=http://localhost:${PORT}
# Domain Configuration (for nginx/SSL)
WEBUI_DOMAIN=${WEBUI_DOMAIN}
# ============================================
# Web3 Payment Configuration (FULA Token)
# ============================================
# Vault address to receive FULA payments
# IMPORTANT: Set this to your actual wallet address to enable payments
VAULT_ADDRESS=${VAULT_ADDRESS:-0x0000000000000000000000000000000000000000}
# Free tier storage limit in bytes (default: 500MB)
FREE_TIER_BYTES=${FREE_TIER_BYTES:-524288000}
# FULA price per GB per month (default: 3)
FULA_PER_GB_MONTH=${FULA_PER_GB_MONTH:-3}
# Etherscan API key for block scanning (Base/Ethereum)
# Get from: https://etherscan.io/apis
ETHERSCAN_API_KEY=${ETHERSCAN_API_KEY:-}
# Admin emails (comma-separated) - can manage suspended users
ADMIN_EMAILS=${ADMIN_EMAILS:-}
# ============================================
# x402 Gateway Integration
# ============================================
# System key for x402 gateway to adjust credits
# Must match PINNING_SYSTEM_KEY in x402-skale .env
PINNING_SYSTEM_KEY=${PINNING_SYSTEM_KEY:-}
EOF
chmod 600 "$target_dir/pinning-webui/.env"
verify_step "WebUI .env file creation" "[ -f '$target_dir/pinning-webui/.env' ]"
}
# Create WebUI systemd service file
create_webui_service_file() {
local target_dir=$1
print_info "Creating WebUI systemd service file..."
# Get the actual node path
local node_path=$(which node)
cat > "$WEBUI_SERVICE_FILE" << EOF
[Unit]
Description=FULA Pinning Service WebUI
Documentation=https://github.com/functionland/pinning-service
After=network.target fula-pinning-service.service
Wants=network-online.target
StartLimitBurst=5
StartLimitIntervalSec=60
[Service]
Type=simple
ExecStart=${node_path} ${target_dir}/pinning-webui/dist/server.mjs
Restart=on-failure
RestartSec=10
User=root
WorkingDirectory=${target_dir}/pinning-webui
Environment=PATH=/usr/bin:/usr/local/bin:/usr/local/node/bin
Environment=NODE_ENV=production
EnvironmentFile=${target_dir}/pinning-webui/.env
# Security hardening
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=false
ReadWritePaths=${target_dir}/data ${target_dir}/pinning-webui
# Resource limits
LimitNOFILE=65535
MemoryMax=512M
# Logging
StandardOutput=journal
StandardError=journal
SyslogIdentifier=${WEBUI_SERVICE_NAME}
[Install]
WantedBy=multi-user.target
EOF
chmod 644 "$WEBUI_SERVICE_FILE"
verify_step "WebUI service file creation" "[ -f '$WEBUI_SERVICE_FILE' ]"
}
# Configure and start WebUI service
configure_webui_service() {
print_info "Configuring WebUI systemd service..."
systemctl daemon-reload
systemctl enable "$WEBUI_SERVICE_NAME"
verify_step "WebUI service configuration" "systemctl is-enabled '$WEBUI_SERVICE_NAME'"
}
# Start WebUI service
start_webui_service() {
print_info "Starting WebUI service..."
systemctl start "$WEBUI_SERVICE_NAME"
sleep 3
if systemctl is-active --quiet "$WEBUI_SERVICE_NAME"; then
print_success "WebUI service started successfully"
else
print_error "WebUI service failed to start"
journalctl -u "$WEBUI_SERVICE_NAME" -n 20 --no-pager
return 1
fi
}
# Configure systemd service
configure_service() {
print_info "Configuring systemd service..."
systemctl daemon-reload
verify_step "Systemd daemon reload" "true"
systemctl enable "$SERVICE_NAME"
verify_step "Service enable" "systemctl is-enabled --quiet $SERVICE_NAME"
}
# Configure gateway systemd service
configure_gateway_service() {
print_info "Configuring gateway systemd service..."
systemctl daemon-reload
systemctl enable "$GATEWAY_SERVICE_NAME"
verify_step "Gateway service enable" "systemctl is-enabled --quiet $GATEWAY_SERVICE_NAME"
}
# Start the gateway service
start_gateway_service() {
print_info "Starting gateway service..."
systemctl start "$GATEWAY_SERVICE_NAME"
sleep 3
if systemctl is-active --quiet "$GATEWAY_SERVICE_NAME"; then
print_success "Gateway service started successfully"
return 0
else
print_warning "Gateway service failed to start. Check logs with: journalctl -u $GATEWAY_SERVICE_NAME -f"
return 1
fi
}
# Start the service
start_service() {
print_info "Starting service..."
systemctl start "$SERVICE_NAME"
sleep 3
if systemctl is-active --quiet "$SERVICE_NAME"; then
print_success "Service started successfully"
return 0
else
print_error "Service failed to start. Check logs with: journalctl -u $SERVICE_NAME -f"
return 1
fi
}
# Backup existing installation
backup_existing() {
local target_dir=$1
local backup_dir="${target_dir}.backup.$(date +%Y%m%d_%H%M%S)"
print_info "Backing up existing installation to $backup_dir..."
cp -r "$target_dir" "$backup_dir"
verify_step "Backup" "[ -d '$backup_dir' ]"
}
# Initialize database (run a quick check)
init_database() {
local target_dir=$1
print_info "Initializing database..."
# The application will create tables on first run
# Just ensure the data directory exists and is writable
touch "$target_dir/data/.init_check"
rm -f "$target_dir/data/.init_check"
print_success "Database directory ready"
}
# ============================================================================
# Nginx and SSL/Certbot Functions
# ============================================================================
# Check if nginx is installed
check_nginx_installed() {
if command -v nginx &> /dev/null; then
return 0
fi
return 1
}
# Install nginx if not present
install_nginx() {
if check_nginx_installed; then
print_info "Nginx is already installed"
return 0
fi
print_info "Installing nginx..."
if command -v apt-get &> /dev/null; then
apt-get update
apt-get install -y nginx
elif command -v yum &> /dev/null; then
yum install -y nginx
elif command -v dnf &> /dev/null; then
dnf install -y nginx
else
print_error "Could not determine package manager. Please install nginx manually."
return 1
fi
systemctl enable nginx
systemctl start nginx
verify_step "Nginx installation" "check_nginx_installed"
}
# Install certbot if not present
install_certbot() {
if command -v certbot &> /dev/null; then
print_info "Certbot is already installed"
return 0
fi
print_info "Installing certbot..."
if command -v apt-get &> /dev/null; then
apt-get update
apt-get install -y certbot python3-certbot-nginx
elif command -v yum &> /dev/null; then
yum install -y certbot python3-certbot-nginx
elif command -v dnf &> /dev/null; then
dnf install -y certbot python3-certbot-nginx
else
print_error "Could not determine package manager. Please install certbot manually."
return 1
fi
verify_step "Certbot installation" "command -v certbot &> /dev/null"
}
# Check if nginx config exists for domain
check_nginx_config_exists() {
local domain=$1
if [ -f "$NGINX_AVAILABLE/$domain" ] || [ -f "$NGINX_AVAILABLE/${domain}.conf" ]; then
return 0
fi
return 1
}
# Check if SSL certificate exists and is valid for domain
check_ssl_exists() {
local domain=$1
if [ -d "/etc/letsencrypt/live/$domain" ]; then
# Check if cert is not expired (valid for at least 7 days)
if openssl x509 -checkend 604800 -noout -in "/etc/letsencrypt/live/$domain/fullchain.pem" 2>/dev/null; then
return 0
fi
fi
return 1
}
# Check if nginx config exists, is enabled, and nginx is running properly
check_nginx_config_valid() {
local domain=$1
# Check if config file exists
if [ ! -f "$NGINX_AVAILABLE/$domain" ]; then
return 1
fi
# Check if it's enabled (symlink exists)
if [ ! -L "$NGINX_ENABLED/$domain" ]; then
return 1
fi
# Check if nginx config test passes
if ! nginx -t 2>/dev/null; then
return 1
fi
# Check if nginx is running
if ! systemctl is-active --quiet nginx; then
return 1
fi
return 0
}
# Create nginx configuration for the services
create_nginx_config() {
local domain=$1
local target_dir=$2
local pinning_port=$3
local gateway_port=$4
print_info "Creating nginx configuration for $domain..."
local config_file="$NGINX_AVAILABLE/$domain"
cat > "$config_file" << EOF
# Nginx configuration for IPFS Pinning Service
# Domain: $domain
# Generated on $(date)
# Upstream servers
upstream pinning_service {
server 127.0.0.1:$pinning_port;
keepalive 32;
}
upstream gateway_service {
server 127.0.0.1:$gateway_port;
keepalive 32;
}
# HTTP server - redirect to HTTPS (will be modified by certbot)
server {
listen 80;
listen [::]:80;
server_name $domain;
# Allow ACME challenge
location /.well-known/acme-challenge/ {
root ${target_dir}/ipfs-server;
allow all;
}
# Redirect all other traffic to HTTPS
location / {
return 301 https://\$host\$request_uri;
}
}
# HTTPS server (certbot will add SSL config)
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name $domain;
# SSL configuration will be added by certbot
# ssl_certificate /etc/letsencrypt/live/$domain/fullchain.pem;
# ssl_certificate_key /etc/letsencrypt/live/$domain/privkey.pem;
# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# Logging
access_log /var/log/nginx/${domain}_access.log;
error_log /var/log/nginx/${domain}_error.log;
# Client body size for file uploads
client_max_body_size 800M;
# Timeouts
proxy_connect_timeout 60s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
# Pinning Service API (/pins, /admin, etc.)
location /pins {
proxy_pass http://pinning_service;
proxy_http_version 1.1;
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
proxy_set_header Connection "";
# CORS headers
add_header Access-Control-Allow-Origin "*" always;
add_header Access-Control-Allow-Methods "GET, POST, DELETE, OPTIONS" always;
add_header Access-Control-Allow-Headers "Authorization, Content-Type" always;
if (\$request_method = OPTIONS) {
return 204;
}
}
location /admin {
proxy_pass http://pinning_service;
proxy_http_version 1.1;
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
proxy_set_header Connection "";
}
# IPFS Gateway (/gateway, /upload)
location /gateway {
proxy_pass http://gateway_service;
proxy_http_version 1.1;
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
proxy_set_header Connection "";
# Cache for immutable IPFS content
proxy_cache_valid 200 365d;
add_header Cache-Control "public, max-age=31536000, immutable";
# CORS headers
add_header Access-Control-Allow-Origin "*" always;
add_header Access-Control-Allow-Methods "GET, OPTIONS" always;
add_header Access-Control-Allow-Headers "*" always;
}
location /upload {
proxy_pass http://gateway_service;
proxy_http_version 1.1;
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
proxy_set_header Connection "";
# Large file upload timeout
proxy_read_timeout 600s;
}
location /health {
proxy_pass http://gateway_service;
proxy_http_version 1.1;
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
}
# Default - serve pinning service
location / {