-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlnvps-routstr-openclaw.sh
More file actions
executable file
·1472 lines (1276 loc) · 51.9 KB
/
Copy pathlnvps-routstr-openclaw.sh
File metadata and controls
executable file
·1472 lines (1276 loc) · 51.9 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
set -e
# LNVPS CLI Deployment Script
# Requires: nak, jq, curl
API_BASE="https://api.lnvps.net/api/v1"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
CDK_CLI_DIR="$SCRIPT_DIR/temp-routstr"
CDK_CLI_BIN="$CDK_CLI_DIR/cdk-cli-v0.13.0"
CDK_CLI_URL="https://github.com/cashubtc/cdk/releases/download/v0.13.0/cdk-cli-v0.13.0"
MINT_URL="https://mint.cubabitcoin.org"
echo "=== LNVPS VPS Deployment Script ==="
echo ""
# Detect operating system
case "$(uname -s)" in
Linux*) OS_TYPE="linux";;
Darwin*) OS_TYPE="mac";;
CYGWIN*|MINGW*|MSYS*|Windows_NT*)
echo "Error: Windows is not supported"
exit 1
;;
*)
echo "Error: Unknown operating system: $(uname -s)"
exit 1
;;
esac
echo "Detected OS: $OS_TYPE"
echo ""
# Function to install jq
install_jq() {
if ! command -v jq >/dev/null 2>&1; then
echo "jq not found. Attempting to install..."
if [ "$OS_TYPE" = "mac" ]; then
if command -v brew >/dev/null 2>&1; then
brew install jq
else
echo "Error: Homebrew is required to install jq on macOS."
echo "Please install Homebrew or install jq manually."
exit 1
fi
elif [ "$OS_TYPE" = "linux" ]; then
if command -v apt-get >/dev/null 2>&1; then
SUDO=""
[ "$(id -u)" -ne 0 ] && command -v sudo >/dev/null 2>&1 && SUDO="sudo"
$SUDO apt-get update && $SUDO apt-get install -y jq
elif command -v yum >/dev/null 2>&1; then
SUDO=""
[ "$(id -u)" -ne 0 ] && command -v sudo >/dev/null 2>&1 && SUDO="sudo"
$SUDO yum install -y jq
elif command -v apk >/dev/null 2>&1; then
SUDO=""
[ "$(id -u)" -ne 0 ] && command -v sudo >/dev/null 2>&1 && SUDO="sudo"
$SUDO apk add jq
elif command -v pacman >/dev/null 2>&1; then
SUDO=""
[ "$(id -u)" -ne 0 ] && command -v sudo >/dev/null 2>&1 && SUDO="sudo"
$SUDO pacman -S --noconfirm jq
else
echo "Error: Could not detect package manager to install jq."
echo "Please install jq manually."
exit 1
fi
else
echo "Error: Unsupported OS for automatic installation."
echo "Please install jq manually."
exit 1
fi
# Verify installation
if ! command -v jq >/dev/null 2>&1; then
echo "Error: Failed to install jq."
exit 1
fi
echo "jq installed successfully."
fi
}
# Check dependencies
command -v nak >/dev/null 2>&1 || { curl -sSL https://raw.githubusercontent.com/fiatjaf/nak/master/install.sh | sh; }
install_jq
command -v curl >/dev/null 2>&1 || { echo "Error: curl is required"; exit 1; }
# Setup temp-routstr, cdk-cli, and uv/qrcode
mkdir -p "$CDK_CLI_DIR"
if [ "$OS_TYPE" != "mac" ] && [ ! -f "$CDK_CLI_BIN" ]; then
echo "=== Downloading cdk-cli ==="
curl -LsSf "$CDK_CLI_URL" -o "$CDK_CLI_BIN"
chmod +x "$CDK_CLI_BIN"
fi
if ! command -v uv >/dev/null 2>&1; then
echo "=== Installing uv package manager ==="
curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"
fi
if [ ! -f "$CDK_CLI_DIR/pyproject.toml" ]; then
echo "=== Initializing Python project ==="
cd "$CDK_CLI_DIR"
uv init . 2>/dev/null || true
fi
cd "$CDK_CLI_DIR"
if ! grep -q "qrcode" pyproject.toml 2>/dev/null; then
echo "=== Adding qrcode package ==="
uv add qrcode
fi
cd "$SCRIPT_DIR"
# Nostr config file path (in current directory)
NOSTR_CONFIG_FILE="./nostr.config.json"
# Function to save nostr config
save_nostr_config() {
local hex_key="$1"
local nsec_key="$2"
local pubkey_hex="$3"
local npub="$4"
cat > "$NOSTR_CONFIG_FILE" << EOF
{
"generated_at": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
"private_key": {
"hex": "$hex_key",
"nsec": "$nsec_key"
},
"public_key": {
"hex": "$pubkey_hex",
"npub": "$npub"
}
}
EOF
echo "Nostr config saved to $NOSTR_CONFIG_FILE"
}
# Function to print QR code for invoices
print_qr_code() {
local invoice="$1"
./temp-routstr/.venv/bin/python -c "
import qrcode
invoice = '''$invoice'''
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=1,
border=1,
)
qr.add_data(invoice)
qr.make(fit=True)
# Print QR code using Unicode half-blocks to reduce height
matrix = qr.get_matrix()
height = len(matrix)
width = len(matrix[0]) if height else 0
for y in range(0, height, 2):
line = ''
for x in range(width):
top = matrix[y][x]
bottom = matrix[y + 1][x] if y + 1 < height else False
if top and bottom:
line += '\u2588'
elif top and not bottom:
line += '\u2580'
elif not top and bottom:
line += '\u2584'
else:
line += ' '
print(line)
"
}
# Check for existing nostr.config.json file
NSEC=""
HEX_KEY=""
if [ -f "$NOSTR_CONFIG_FILE" ]; then
echo "Found existing nostr.config.json file..."
# Try to read private key from config
CONFIG_HEX=$(jq -r '.private_key.hex // empty' "$NOSTR_CONFIG_FILE" 2>/dev/null)
CONFIG_NSEC=$(jq -r '.private_key.nsec // empty' "$NOSTR_CONFIG_FILE" 2>/dev/null)
if [ -n "$CONFIG_HEX" ] && [ "$CONFIG_HEX" != "null" ]; then
echo "Using private key from nostr.config.json"
HEX_KEY="$CONFIG_HEX"
NSEC="$CONFIG_HEX"
# Verify the key is valid
PUBKEY_HEX=$(nak key public "$HEX_KEY" 2>/dev/null)
if [ -z "$PUBKEY_HEX" ]; then
echo "Warning: Private key in config is invalid. Will prompt for new key."
HEX_KEY=""
NSEC=""
fi
fi
fi
# If no valid key from config, prompt user
if [ -z "$HEX_KEY" ]; then
echo "Enter your Nostr private key (nsec or hex), or press enter to generate one: "
# Disable terminal echo
stty -echo
while IFS= read -r -n1 char; do
if [[ "$char" == "" ]]; then
break
elif [[ "$char" == $'\x7f' ]] || [[ "$char" == $'\b' ]]; then
if [[ -n "$NSEC" ]]; then
NSEC="${NSEC%?}"
echo -ne "\b \b"
fi
else
NSEC+="$char"
echo -n "•"
fi
done
# Re-enable terminal echo
stty echo
echo ""
if [ -z "$NSEC" ]; then
echo "No key entered. Generating a new Nostr private key..."
NSEC=$(nak key generate 2>/dev/null || true)
if [ -z "$NSEC" ]; then
echo "Error: Failed to generate a private key"
exit 1
fi
echo "Generated new private key. It is stored in nostr.config.json."
fi
# Handle both nsec (bech32) and hex private key formats
if [[ "$NSEC" == nsec1* ]]; then
# Decode nsec to hex for nak key public
HEX_KEY=$(nak decode "$NSEC" 2>/dev/null)
if [ -z "$HEX_KEY" ]; then
echo "Error: Invalid nsec"
exit 1
fi
else
# Assume hex format
HEX_KEY="$NSEC"
fi
fi
# Get public key (hex) from private key
PUBKEY_HEX=$(nak key public "$HEX_KEY" 2>/dev/null)
if [ -z "$PUBKEY_HEX" ]; then
echo "Error: Invalid private key"
exit 1
fi
# Encode public key to npub for display
NPUB=$(nak encode npub "$PUBKEY_HEX" 2>/dev/null)
if [ -z "$NPUB" ]; then
echo "Error: Failed to encode public key"
exit 1
fi
# Encode private key to nsec for storage
NSEC_ENCODED=$(nak encode nsec "$HEX_KEY" 2>/dev/null || echo "")
# Save to config file if it doesn't exist or was invalid
if [ ! -f "$NOSTR_CONFIG_FILE" ] || [ -z "$(jq -r '.private_key.hex // empty' "$NOSTR_CONFIG_FILE" 2>/dev/null)" ]; then
save_nostr_config "$HEX_KEY" "$NSEC_ENCODED" "$PUBKEY_HEX" "$NPUB"
fi
echo "Authenticated as: $NPUB"
echo ""
# Function to create NIP-98 auth event
# Usage: nip98_auth <method> <url> [payload]
nip98_auth() {
local method="$1"
local url="$2"
local payload="${3:-}"
local signed_event
# If there's a payload, include payload hash tag
if [ -n "$payload" ]; then
local payload_hash=$(echo -n "$payload" | sha256sum | cut -d' ' -f1)
signed_event=$(nak event -k 27235 -c "" \
-t "u=$url" \
-t "method=$method" \
-t "payload=$payload_hash" \
--sec "$NSEC" 2>/dev/null)
else
signed_event=$(nak event -k 27235 -c "" \
-t "u=$url" \
-t "method=$method" \
--sec "$NSEC" 2>/dev/null)
fi
# Encode as base64 for Authorization header (macOS base64 doesn't have -w flag)
if [ "$OS_TYPE" = "mac" ]; then
echo "$signed_event" | base64
else
echo "$signed_event" | base64 -w 0
fi
}
# Function to make authenticated API call
api_call() {
local method="$1"
local endpoint="$2"
local payload="${3:-}"
local url="${API_BASE}${endpoint}"
local auth_token=$(nip98_auth "$method" "$url" "$payload")
if [ -n "$payload" ]; then
curl -s -X "$method" \
-H "Authorization: Nostr $auth_token" \
-H "Content-Type: application/json" \
-d "$payload" \
"$url"
else
curl -s -X "$method" \
-H "Authorization: Nostr $auth_token" \
"$url"
fi
}
# Function to format timestamp
format_date() {
local timestamp="$1"
if [ -n "$timestamp" ] && [ "$timestamp" != "null" ]; then
if [ "$OS_TYPE" = "mac" ]; then
date -r "$timestamp" "+%Y-%m-%d %H:%M" 2>/dev/null || echo "$timestamp"
else
date -d "@$timestamp" "+%Y-%m-%d %H:%M" 2>/dev/null || echo "$timestamp"
fi
else
echo "N/A"
fi
}
# Function to calculate days until expiry
days_until() {
local date_str="$1"
if [ -n "$date_str" ] && [ "$date_str" != "null" ]; then
local expiry_ts=""
if [ "$OS_TYPE" = "mac" ]; then
# Try to parse ISO format on Mac
expiry_ts=$(date -j -f "%Y-%m-%dT%H:%M:%S" "${date_str%%.*}" +%s 2>/dev/null)
else
expiry_ts=$(date -d "$date_str" +%s 2>/dev/null)
fi
if [ -n "$expiry_ts" ]; then
local now=$(date +%s)
local diff=$(( (expiry_ts - now) / 86400 ))
echo "$diff"
else
echo "?"
fi
else
echo "?"
fi
}
SKIP_CREATION=false
# Check for existing VMs
echo "Checking for existing VMs..."
vms_response=$(api_call "GET" "/vm")
vms=$(echo "$vms_response" | jq -r '.data // []')
if [ -n "$vms" ] && [ "$vms" != "[]" ] && [ "$vms" != "null" ]; then
echo ""
echo "=== Existing VMs ==="
echo ""
# Build VM list with indexes
vm_opt_num=1
vm_options_ids=()
# Save VM data to temp file to avoid subshell issues
echo "$vms" | jq -c '.[]' > /tmp/lnvps_vms_$$
while IFS= read -r vm; do
id=$(echo "$vm" | jq -r '.id')
status=$(echo "$vm" | jq -r '.status.state // "unknown"')
ip=$(echo "$vm" | jq -r '.ip_assignments[0].ip // "pending"')
expires=$(echo "$vm" | jq -r '.expires // null')
expiry_str="N/A"
if [ -n "$expires" ] && [ "$expires" != "null" ]; then
days=$(days_until "$expires")
if [ "$days" != "?" ]; then
expiry_str="$days days"
fi
fi
printf " [%d] VM %s | %-7s | %-16s | %s\n" "$vm_opt_num" "$id" "$status" "$ip" "$expiry_str"
vm_options_ids[$vm_opt_num]="$id"
vm_opt_num=$((vm_opt_num + 1))
done < /tmp/lnvps_vms_$$
rm -f /tmp/lnvps_vms_$$
# Add option to create new VM
echo ""
echo " [$vm_opt_num] Create a new VM"
create_new_option=$vm_opt_num
echo ""
echo -n "Enter your choice [1-$vm_opt_num] (enter = default 1): "
read vm_choice
if [ -z "$vm_choice" ]; then
vm_choice=1
fi
if [ "$vm_choice" -eq "$create_new_option" ] 2>/dev/null; then
echo "Creating a new VM..."
elif [ -n "${vm_options_ids[$vm_choice]}" ]; then
use_vm_id="${vm_options_ids[$vm_choice]}"
echo "Fetching details for VM $use_vm_id..."
vm_details_resp=$(api_call "GET" "/vm/${use_vm_id}")
vm_data=$(echo "$vm_details_resp" | jq -r '.data // null')
if [ -n "$vm_data" ] && [ "$vm_data" != "null" ]; then
echo "Selected VM $use_vm_id"
SKIP_CREATION=true
vm_id="$use_vm_id"
vm_state=$(echo "$vm_data" | jq -r '.status.state // "unknown"')
vm_ip=$(echo "$vm_data" | jq -r '.ip_assignments[0].ip // "pending"')
vm_expires=$(echo "$vm_data" | jq -r '.expires // null')
vm_days="?"
if [ -n "$vm_expires" ] && [ "$vm_expires" != "null" ]; then
vm_days=$(days_until "$vm_expires")
fi
if [ "$vm_state" = "stopped" ]; then
# Check if VM needs payment (stopped + pending IP + 0 days)
if [ "$vm_ip" = "pending" ] && [ "$vm_days" = "0" ]; then
echo "VM is stopped and requires payment to be activated."
echo -n "Do you want to pay for this VM? [Y/n] "
read pay_choice
if [[ "$pay_choice" =~ ^[Yy] ]] || [ -z "$pay_choice" ]; then
echo "Getting payment invoice..."
renew_resp=$(api_call "GET" "/vm/${vm_id}/renew")
payment=$(echo "$renew_resp" | jq -r '.data // null')
if [ -n "$payment" ] && [ "$payment" != "null" ]; then
payment_id=$(echo "$payment" | jq -r '.id')
invoice=$(echo "$payment" | jq -r '.data.lightning // .invoice')
amount=$(echo "$payment" | jq -r '.amount')
amount=$((amount / 1000))
echo ""
echo "Payment Invoice ($amount sats):"
echo "$invoice"
echo ""
print_qr_code "$invoice"
echo "Waiting for payment..."
while true; do
sleep 5
chk=$(api_call "GET" "/payment/${payment_id}")
paid=$(echo "$chk" | jq -r '.data.is_paid')
if [ "$paid" = "true" ]; then
echo "Payment received!"
echo "Waiting for VM to start..."
sleep 5
break
fi
done
else
echo "Error: Could not get payment invoice."
exit 1
fi
else
echo "Cannot proceed without payment."
exit 1
fi
else
echo "VM is stopped."
echo -n "Do you want to start this VM? [Y/n] "
read start_choice
if [[ "$start_choice" =~ ^[Yy] ]] || [ -z "$start_choice" ]; then
echo "Starting VM..."
start_resp=$(api_call "PATCH" "/vm/${vm_id}/start")
echo "VM start command sent."
echo "Waiting for VM to start..."
sleep 5
else
echo "Cannot proceed with stopped VM."
exit 1
fi
fi
elif [ "$vm_state" = "expired" ]; then
echo "VM is expired."
echo -n "Do you want to renew this VM? [Y/n] "
read renew_choice
if [[ "$renew_choice" =~ ^[Yy] ]] || [ -z "$renew_choice" ]; then
echo "Getting renewal invoice..."
renew_resp=$(api_call "GET" "/vm/${vm_id}/renew")
payment=$(echo "$renew_resp" | jq -r '.data // null')
if [ -n "$payment" ] && [ "$payment" != "null" ]; then
payment_id=$(echo "$payment" | jq -r '.id')
invoice=$(echo "$payment" | jq -r '.data.lightning // .invoice')
amount=$(echo "$payment" | jq -r '.amount')
amount=$((amount / 1000))
echo ""
echo "Renewal Invoice ($amount sats):"
echo "$invoice"
echo ""
print_qr_code "$invoice"
echo "Waiting for payment..."
while true; do
sleep 5
chk=$(api_call "GET" "/payment/${payment_id}")
paid=$(echo "$chk" | jq -r '.data.is_paid')
if [ "$paid" = "true" ]; then
echo "Payment received!"
break
fi
done
else
echo "Error: Could not get renewal invoice."
exit 1
fi
else
echo "Cannot proceed with expired VM without renewal."
exit 1
fi
elif [ "$vm_state" = "running" ]; then
echo "VM is already running."
fi
echo ""
echo "To configure this VM, we need the local SSH private key."
echo ""
# Fetch SSH keys from API
echo "Fetching your SSH keys from LNVPS..."
existing_ssh_keys_response=$(api_call "GET" "/ssh-key")
existing_ssh_keys=$(echo "$existing_ssh_keys_response" | jq -r '.data // []')
# Find local SSH private keys (look for .pub files and derive private key paths)
existing_local_keys=()
existing_key_paths=()
if [ -d "$HOME/.ssh" ]; then
find "$HOME/.ssh" -maxdepth 1 -name "*.pub" 2>/dev/null > /tmp/lnvps_existing_keys_$$
while IFS= read -r pubkey; do
if [ -n "$pubkey" ]; then
priv_key="${pubkey%.pub}"
if [ -f "$priv_key" ]; then
existing_local_keys+=("$pubkey")
existing_key_paths+=("$priv_key")
fi
fi
done < /tmp/lnvps_existing_keys_$$
rm -f /tmp/lnvps_existing_keys_$$
fi
echo ""
echo "=== SSH Key Selection ==="
echo ""
existing_opt_num=1
existing_options_values=()
default_option=1
# List API keys first (so they become default)
if [ -n "$existing_ssh_keys" ] && [ "$existing_ssh_keys" != "[]" ] && [ "$existing_ssh_keys" != "null" ]; then
echo "Already uploaded to LNVPS:"
echo "$existing_ssh_keys" | jq -r '.[] | "\(.id)|\(.name)"' > /tmp/lnvps_existing_api_keys_$$
while IFS= read -r line; do
key_id=$(echo "$line" | cut -d'|' -f1)
key_name=$(echo "$line" | cut -d'|' -f2)
echo " [$existing_opt_num] $key_name (ID: $key_id)"
existing_options_values[$existing_opt_num]="api:$key_id:$key_name"
existing_opt_num=$((existing_opt_num + 1))
done < /tmp/lnvps_existing_api_keys_$$
rm -f /tmp/lnvps_existing_api_keys_$$
echo ""
fi
# List local SSH keys
if [ ${#existing_local_keys[@]} -gt 0 ]; then
echo "Local SSH keys (~/.ssh/):"
for i in "${!existing_local_keys[@]}"; do
pubkey="${existing_local_keys[$i]}"
key_name=$(basename "$pubkey" .pub)
key_type=$(awk '{print $1}' "$pubkey" | sed 's/ssh-//')
key_comment=$(awk '{print $3}' "$pubkey")
echo " [$existing_opt_num] $key_name ($key_type) ${key_comment:+- $key_comment}"
existing_options_values[$existing_opt_num]="local:$pubkey"
existing_opt_num=$((existing_opt_num + 1))
done
echo ""
fi
if [ $((existing_opt_num - 1)) -eq 0 ]; then
echo "No SSH keys found."
echo "Using default: ~/.ssh/id_rsa"
ssh_private_key="$HOME/.ssh/id_rsa"
else
echo -n "Enter your choice [1-$((existing_opt_num-1))] (enter = default $default_option): "
read key_choice
if [ -z "$key_choice" ]; then
key_choice=$default_option
fi
if [ -z "${existing_options_values[$key_choice]}" ]; then
echo "Invalid selection, using default."
key_choice=$default_option
fi
selected_key="${existing_options_values[$key_choice]}"
if [[ "$selected_key" == local:* ]]; then
pubkey_path="${selected_key#local:}"
ssh_private_key="${pubkey_path%.pub}"
echo "Using private key: $ssh_private_key"
elif [[ "$selected_key" == api:* ]]; then
selected_content="${selected_key#api:}"
api_key_id=$(echo "$selected_content" | cut -d':' -f1)
api_key_name=$(echo "$selected_content" | cut -d':' -f2)
echo "Using existing SSH key ID: $api_key_id"
# Check if key exists locally by name
if [ -n "$api_key_name" ] && [ -f "$HOME/.ssh/$api_key_name" ]; then
ssh_private_key="$HOME/.ssh/$api_key_name"
echo "Found local key: $ssh_private_key"
elif [ -f "$HOME/.ssh/$api_key_id" ]; then
ssh_private_key="$HOME/.ssh/$api_key_id"
echo "Found local key: $ssh_private_key"
else
echo ""
echo "Please provide the path to your local SSH private key:"
echo -n "Path (default: ~/.ssh/id_rsa): "
read ssh_private_key
ssh_private_key="${ssh_private_key:-$HOME/.ssh/id_rsa}"
ssh_private_key="${ssh_private_key/#\~/$HOME}"
fi
echo "Using private key: $ssh_private_key"
fi
fi
if [ ! -f "$ssh_private_key" ]; then
echo "Warning: Key file not found at $ssh_private_key"
fi
else
echo "VM ID not found. Creating new VM."
fi
else
echo "Invalid selection, creating new VM."
fi
fi
if [ "$SKIP_CREATION" = "false" ]; then
# Desired custom VM specs
DESIRED_CPU=2
DESIRED_MEMORY=2147483648 # 2 GB in bytes
DESIRED_DISK=42949672960 # 40 GB in bytes
DESIRED_DISK_TYPE="ssd"
DESIRED_DISK_INTERFACE="pcie"
# Get available VM templates
echo "Fetching available VM templates..."
templates_response=$(curl -s "${API_BASE}/vm/templates")
templates=$(echo "$templates_response" | jq -r '.data.templates // []')
custom_templates=$(echo "$templates_response" | jq -r '.data.custom_template // []')
if [ -z "$templates" ] || [ "$templates" = "[]" ] || [ "$templates" = "null" ]; then
echo "Error: Could not fetch templates"
exit 1
fi
# Function to check if custom template supports our desired specs
check_custom_template() {
local region_name="$1"
local ct=$(echo "$custom_templates" | jq -r ".[] | select(.region.name | test(\"$region_name\"))")
if [ -z "$ct" ] || [ "$ct" = "null" ]; then
return 1
fi
local pricing_id=$(echo "$ct" | jq -r '.id')
local min_cpu=$(echo "$ct" | jq -r '.min_cpu')
local max_cpu=$(echo "$ct" | jq -r '.max_cpu')
local min_mem=$(echo "$ct" | jq -r '.min_memory')
local max_mem=$(echo "$ct" | jq -r '.max_memory')
# Check CPU bounds
if [ "$DESIRED_CPU" -lt "$min_cpu" ] || [ "$DESIRED_CPU" -gt "$max_cpu" ]; then
return 1
fi
# Check memory bounds
if [ "$DESIRED_MEMORY" -lt "$min_mem" ] || [ "$DESIRED_MEMORY" -gt "$max_mem" ]; then
return 1
fi
# Check disk bounds for SSD
local disk_ok=$(echo "$ct" | jq -r ".disks[] | select(.disk_type == \"$DESIRED_DISK_TYPE\" and .disk_interface == \"$DESIRED_DISK_INTERFACE\") | select(.min_disk <= $DESIRED_DISK and .max_disk >= $DESIRED_DISK) | .disk_type")
if [ -z "$disk_ok" ]; then
return 1
fi
echo "$pricing_id"
return 0
}
# Try to get custom template pricing
get_custom_price() {
local pricing_id="$1"
local price_response=$(curl -s "${API_BASE}/vm/custom-template/price" \
-X POST \
-H "Content-Type: application/json" \
-d "{\"pricing_id\": $pricing_id, \"cpu\": $DESIRED_CPU, \"memory\": $DESIRED_MEMORY, \"disk\": $DESIRED_DISK, \"disk_type\": \"$DESIRED_DISK_TYPE\", \"disk_interface\": \"$DESIRED_DISK_INTERFACE\"}")
local amount=$(echo "$price_response" | jq -r '.data.amount // empty')
local currency=$(echo "$price_response" | jq -r '.data.currency // empty')
if [ -n "$amount" ] && [ "$amount" != "null" ]; then
echo "$amount|$currency"
return 0
fi
return 1
}
USE_CUSTOM_TEMPLATE=false
CUSTOM_PRICING_ID=""
CUSTOM_REGION_NAME=""
echo ""
echo "Checking for custom VM configuration (2 CPU, 2GB RAM, 40GB SSD)..."
# Try Dublin first
dublin_pricing_id=$(check_custom_template "Dublin")
if [ -n "$dublin_pricing_id" ]; then
price_info=$(get_custom_price "$dublin_pricing_id")
if [ -n "$price_info" ]; then
USE_CUSTOM_TEMPLATE=true
CUSTOM_PRICING_ID="$dublin_pricing_id"
CUSTOM_REGION_NAME="Dublin (IE)"
CUSTOM_PRICE=$(echo "$price_info" | cut -d'|' -f1)
CUSTOM_CURRENCY=$(echo "$price_info" | cut -d'|' -f2)
echo " Dublin available: $CUSTOM_PRICE $CUSTOM_CURRENCY/month"
fi
fi
# Try London if Dublin failed
if [ "$USE_CUSTOM_TEMPLATE" = false ]; then
london_pricing_id=$(check_custom_template "London")
if [ -n "$london_pricing_id" ]; then
price_info=$(get_custom_price "$london_pricing_id")
if [ -n "$price_info" ]; then
USE_CUSTOM_TEMPLATE=true
CUSTOM_PRICING_ID="$london_pricing_id"
CUSTOM_REGION_NAME="London (GB)"
CUSTOM_PRICE=$(echo "$price_info" | cut -d'|' -f1)
CUSTOM_CURRENCY=$(echo "$price_info" | cut -d'|' -f2)
echo " London available: $CUSTOM_PRICE $CUSTOM_CURRENCY/month"
fi
fi
fi
if [ "$USE_CUSTOM_TEMPLATE" = true ]; then
echo ""
echo "Custom VM configuration selected:"
echo " Region: $CUSTOM_REGION_NAME"
echo " CPU: $DESIRED_CPU cores"
echo " RAM: $((DESIRED_MEMORY / 1024 / 1024 / 1024)) GB"
echo " Disk: $((DESIRED_DISK / 1024 / 1024 / 1024)) GB SSD"
echo " Cost: $CUSTOM_PRICE $CUSTOM_CURRENCY/month"
echo ""
else
# Fall back to showing available templates
echo ""
echo "Custom configuration not available. Please select a template:"
echo ""
echo "Available VM Templates:"
echo "========================================"
template_count=$(echo "$templates" | jq 'length')
for i in $(seq 0 $((template_count - 1))); do
t=$(echo "$templates" | jq ".[$i]")
t_id=$(echo "$t" | jq -r '.id')
t_name=$(echo "$t" | jq -r '.name')
t_cpu=$(echo "$t" | jq -r '.cpu')
t_ram=$(echo "$t" | jq -r '.memory')
t_disk=$(echo "$t" | jq -r '.disk_size')
t_cost=$(echo "$t" | jq -r '.cost_plan.amount')
t_currency=$(echo "$t" | jq -r '.cost_plan.currency')
t_region=$(echo "$t" | jq -r '.region.name')
ram_gb=$((t_ram / 1024 / 1024 / 1024))
disk_gb=$((t_disk / 1024 / 1024 / 1024))
echo " [$((i + 1))] $t_name - ${t_cpu} CPU, ${ram_gb}GB RAM, ${disk_gb}GB - $t_cost $t_currency/mo ($t_region)"
done
echo ""
echo -n "Enter your choice [1-$template_count]: "
read template_choice
if [ -z "$template_choice" ] || [ "$template_choice" -lt 1 ] || [ "$template_choice" -gt "$template_count" ]; then
echo "Error: Invalid selection"
exit 1
fi
selected_template=$(echo "$templates" | jq ".[$((template_choice - 1))]")
template_id=$(echo "$selected_template" | jq -r '.id')
template_name=$(echo "$selected_template" | jq -r '.name')
template_cpu=$(echo "$selected_template" | jq -r '.cpu')
template_ram=$(echo "$selected_template" | jq -r '.memory')
template_disk=$(echo "$selected_template" | jq -r '.disk_size')
template_cost=$(echo "$selected_template" | jq -r '.cost_plan.amount')
template_currency=$(echo "$selected_template" | jq -r '.cost_plan.currency')
echo ""
echo "Template selected:"
echo " Name: $template_name"
echo " CPU: ${template_cpu} cores"
echo " RAM: $((template_ram / 1024 / 1024)) MB"
echo " Disk: $((template_disk / 1024 / 1024 / 1024)) GB"
echo " Cost: $template_cost $template_currency/month"
echo ""
fi
# List SSH keys - both local and from API
echo "Fetching your SSH keys from LNVPS..."
ssh_keys_response=$(api_call "GET" "/ssh-key")
ssh_keys=$(echo "$ssh_keys_response" | jq -r '.data // []')
# Find local SSH public keys
local_keys=()
local_key_paths=()
if [ -d "$HOME/.ssh" ]; then
# Use temp file to avoid subshell issues (Bash 3.2 compatible)
find "$HOME/.ssh" -maxdepth 1 -name "*.pub" 2>/dev/null > /tmp/lnvps_local_keys_$$
while IFS= read -r pubkey; do
if [ -n "$pubkey" ]; then
local_keys+=("$pubkey")
local_key_paths+=("$pubkey")
fi
done < /tmp/lnvps_local_keys_$$
rm -f /tmp/lnvps_local_keys_$$
fi
echo ""
echo "=== SSH Key Selection ==="
echo ""
option_num=1
# Use indexed arrays instead of associative arrays for Bash 3.2 compatibility
options_values=()
# List API keys first (so they become default)
if [ -n "$ssh_keys" ] && [ "$ssh_keys" != "[]" ] && [ "$ssh_keys" != "null" ]; then
echo "Already uploaded to LNVPS:"
# Save to temp file to avoid subshell issues with while loop
echo "$ssh_keys" | jq -r '.[] | "\(.id)|\(.name)"' > /tmp/lnvps_api_keys_$$
while IFS= read -r line; do
key_id=$(echo "$line" | cut -d'|' -f1)
key_name=$(echo "$line" | cut -d'|' -f2)
echo " [$option_num] $key_name (ID: $key_id)"
options_values[$option_num]="api:$key_id:$key_name"
option_num=$((option_num + 1))
done < /tmp/lnvps_api_keys_$$
rm -f /tmp/lnvps_api_keys_$$
echo ""
fi
# List local SSH keys
if [ ${#local_keys[@]} -gt 0 ]; then
echo "Local SSH keys (~/.ssh/):"
for pubkey in "${local_key_paths[@]}"; do
key_name=$(basename "$pubkey" .pub)
key_type=$(awk '{print $1}' "$pubkey" | sed 's/ssh-//')
key_comment=$(awk '{print $3}' "$pubkey")
echo " [$option_num] $key_name ($key_type) ${key_comment:+- $key_comment}"
options_values[$option_num]="local:$pubkey"
option_num=$((option_num + 1))
done
echo ""
fi
# Option to generate new key
echo "Generate new key:"
echo " [$option_num] Generate new SSH key (ssh-keygen)"
options_values[$option_num]="generate"
option_num=$((option_num + 1))
echo ""
echo -n "Enter your choice [1-$((option_num-1))] (enter = default 1): "
read ssh_choice
if [ -z "$ssh_choice" ]; then
ssh_choice=1
fi
if [ -z "${options_values[$ssh_choice]}" ]; then
echo "Error: Invalid selection"
exit 1
fi
selected="${options_values[$ssh_choice]}"
if [[ "$selected" == local:* ]]; then
# Upload local key to API
pubkey_path="${selected#local:}"
ssh_private_key="${pubkey_path%.pub}"
key_name=$(basename "$pubkey_path" .pub)
key_data=$(cat "$pubkey_path")
echo ""
echo "Uploading '$key_name' to LNVPS..."
payload=$(jq -n --arg name "$key_name" --arg key "$key_data" '{name: $name, key_data: $key}')
key_response=$(api_call "POST" "/ssh-key" "$payload")
ssh_key_id=$(echo "$key_response" | jq -r '.data.id')
if [ -z "$ssh_key_id" ] || [ "$ssh_key_id" = "null" ]; then
echo "Error: Failed to upload SSH key"
echo "Response: $key_response"
exit 1
fi
echo "SSH key uploaded with ID: $ssh_key_id"
elif [[ "$selected" == api:* ]]; then
# Use existing API key - need local private key path
selected_content="${selected#api:}"
ssh_key_id=$(echo "$selected_content" | cut -d':' -f1)
key_name=$(echo "$selected_content" | cut -d':' -f2)
echo "Using existing SSH key ID: $ssh_key_id"
# Check if key exists locally by name or ID
if [ -n "$key_name" ] && [ -f "$HOME/.ssh/$key_name" ]; then
ssh_private_key="$HOME/.ssh/$key_name"
echo "Found local key: $ssh_private_key"
elif [ -f "$HOME/.ssh/$ssh_key_id" ]; then
ssh_private_key="$HOME/.ssh/$ssh_key_id"
echo "Found local key: $ssh_private_key"
else
echo ""
echo "Please provide the path to your local SSH private key:"
echo -n "Path (default: ~/.ssh/id_rsa): "
read ssh_private_key
ssh_private_key="${ssh_private_key:-$HOME/.ssh/id_rsa}"
# Expand ~ to home directory
ssh_private_key="${ssh_private_key/#\~/$HOME}"
if [ ! -f "$ssh_private_key" ]; then
echo "Error: Private key not found at $ssh_private_key"
exit 1
fi
fi
echo "Using private key: $ssh_private_key"
elif [ "$selected" = "generate" ]; then
# Generate new SSH key
echo ""
echo -n "Enter key name (default: id_rsa): "
read key_name
key_name="${key_name:-id_rsa}"
key_path="$HOME/.ssh/${key_name}"
if [ -f "$key_path" ]; then
echo "Error: Key already exists at $key_path"
exit 1
fi
echo ""
echo "Generating new SSH key..."
ssh-keygen -t rsa -b 4096 -f "$key_path" -N "" -C "$key_name@lnvps"
if [ ! -f "${key_path}.pub" ]; then
echo "Error: Failed to generate SSH key"
exit 1
fi
key_data=$(cat "${key_path}.pub")