-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsetup.sh
More file actions
executable file
·2978 lines (2718 loc) · 125 KB
/
Copy pathsetup.sh
File metadata and controls
executable file
·2978 lines (2718 loc) · 125 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
#!/usr/bin/env bash
set -euo pipefail
set -o errtrace
trap 'echo -e "\n\033[0;31m[ERROR] Unexpected error at line $LINENO in command: $BASH_COMMAND\033[0m"' ERR
# ============================================================================
# TorBox Media Server - All-in-One Setup Script
# Automated setup for a debrid-powered media server using Docker
#
# Components: Prowlarr, Byparr, Decypharr, Seerr,
# Radarr, Sonarr, rclone/FUSE mount, Plex or Jellyfin
#
# Designed for CachyOS (Arch-based) but works on most Linux distros.
# ============================================================================
VERSION="1.0.0"
DRY_RUN=false
SERVICES_STARTED=false
NON_INTERACTIVE=false
SPINNER_PID=""
# Tracks any temp file created by run_with_spinner so the interrupt handler can clean it up.
SPINNER_TMPFILE=""
trap 'cleanup_on_interrupt' INT TERM
cleanup_on_interrupt() {
echo ""
# Kill any background process started by run_with_spinner
if [[ -n "${SPINNER_PID:-}" ]]; then
kill -9 "${SPINNER_PID}" 2>/dev/null || true
fi
# Remove any leftover spinner temp file from an in-flight background command
if [[ -n "${SPINNER_TMPFILE:-}" && -e "${SPINNER_TMPFILE}" ]]; then
rm -f "${SPINNER_TMPFILE}"
fi
# If setup never completed (.env not written), remove partial installation
if [[ ! -f "${ENV_FILE:-}" && -d "${INSTALL_DIR:-}" ]]; then
log_warn "Setup interrupted before completion. Cleaning up partial installation..."
rm -rf "${INSTALL_DIR:-}"
log_info "Partial installation removed. Re-run setup.sh to start fresh."
elif [[ -f "${ENV_FILE:-}" && ! -f "${SETUP_COMPLETE_FILE:-}" ]]; then
# .env exists but setup_complete doesn't — install was interrupted mid-config
log_warn "Setup interrupted during configuration. Cleaning up incomplete installation..."
rm -rf "${INSTALL_DIR:-}"
log_info "Incomplete installation removed. Re-run setup.sh to start fresh."
else
log_warn "Setup interrupted. Re-run to continue where you left off."
fi
exit 130
}
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
INSTALL_DIR="${SCRIPT_DIR}/torbox-media-server"
CONFIG_DIR="${INSTALL_DIR}/configs"
DATA_DIR="${INSTALL_DIR}/data"
MOUNT_DIR="/mnt/torbox-media"
ENV_FILE="${INSTALL_DIR}/.env"
COMPOSE_FILE="${INSTALL_DIR}/docker-compose.yml"
SETUP_COMPLETE_FILE="${INSTALL_DIR}/.setup_complete"
# Docker image versions are pinned directly in docker-compose.yml.
# Generate deterministic-length API keys (32-char hex, matching *arr format)
generate_api_key() {
local key=""
# Try each generator, capturing only on success
if key=$(openssl rand -hex 16 2>/dev/null); then
:
elif key=$(xxd -p -l 16 /dev/urandom 2>/dev/null); then
:
elif key=$(od -An -tx1 -N16 /dev/urandom 2>/dev/null | tr -d ' \t\n'); then
:
elif key=$(head -c 16 /dev/urandom 2>/dev/null | od -An -tx1 | tr -d ' \t\n'); then
:
else
echo ""
return 1
fi
# Normalize: lowercase, strip non-hex, take first 32 chars
key=$(echo "$key" | tr '[:upper:]' '[:lower:]' | tr -cd 'a-f0-9' | head -c 32)
if [[ ${#key} -ne 32 ]]; then
echo ""
return 1
fi
echo "$key"
}
# Generate secure random admin passwords
_gen_admin_pass() {
local p=""
if p=$(openssl rand -base64 16 2>/dev/null | tr -d '/+=' | head -c 16); then
:
elif p=$(head -c 16 /dev/urandom 2>/dev/null | base64 | tr -d '/+=' | head -c 16); then
:
fi
echo "$p"
}
# Colors
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'
print_banner() {
echo -e "${CYAN}"
cat <<'EOF'
╔══════════════════════════════════════════════════════════════╗
║ TorBox Media Server - All-in-One Setup ║
║ ║
║ Prowlarr · Byparr · Decypharr · Seerr ║
║ Radarr · Sonarr · rclone/FUSE · Plex/Jellyfin ║
╚══════════════════════════════════════════════════════════════╝
EOF
echo -e "${NC}"
}
log_info() { echo -e "${GREEN}[INFO]${NC} $*"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
log_error() { echo -e "${RED}[ERROR]${NC} $*"; }
log_step() { echo -e "${BLUE}[STEP]${NC} ${BOLD}$*${NC}"; }
log_section() {
echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${CYAN} $*${NC}"
echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}\n"
}
mask_key() {
local k="$1"
if [[ ${#k} -gt 4 ]]; then echo "${k:0:4}...${k: -4}"; else echo "$k"; fi
}
# Service port registry (single source of truth for all port/label references)
SVC_ORDER=(decypharr prowlarr byparr radarr sonarr seerr)
declare -A SVC_PORTS=(
[decypharr]=8282 [prowlarr]=9696 [byparr]=8191
[radarr]=7878 [sonarr]=8989 [seerr]=5055
)
declare -A SVC_LABELS=(
[decypharr]="Decypharr" [prowlarr]="Prowlarr" [byparr]="Byparr"
[radarr]="Radarr" [sonarr]="Sonarr" [seerr]="Seerr"
)
print_service_urls() {
local svc
for svc in "${SVC_ORDER[@]}"; do
printf " %b%-14s%b http://localhost:%s\n" "$BOLD" "${SVC_LABELS[$svc]}" "$NC" "${SVC_PORTS[$svc]}"
done
if [[ "$MEDIA_SERVER" == "plex" ]]; then
printf " %b%-14s%b http://localhost:32400/web\n" "$BOLD" "Plex" "$NC"
else
printf " %b%-14s%b http://localhost:8096\n" "$BOLD" "Jellyfin" "$NC"
fi
}
# Run a command in the background with a spinner animation
run_with_spinner() {
local msg="$1"
shift
local spin_chars='⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
local tmpfile
tmpfile=$(mktemp /tmp/torbox-setup.XXXXXX)
SPINNER_TMPFILE="$tmpfile" # exposed to cleanup_on_interrupt trap
"$@" >"$tmpfile" 2>&1 &
local pid=$! i=0
SPINNER_PID="$pid"
while kill -0 "$pid" 2>/dev/null; do
printf "\r %s %s" "${spin_chars:i%${#spin_chars}:1}" "$msg"
i=$((i + 1))
sleep 0.1
done
local rc=0
wait "$pid" && rc=0 || rc=$?
printf "\r %-$((${#msg} + 4))s\r" ""
if [[ $rc -ne 0 ]]; then cat "$tmpfile" >&2; fi
rm -f "$tmpfile"
SPINNER_TMPFILE=""
SPINNER_PID=""
return "$rc"
}
# Detect the correct docker compose command and store in COMPOSE_CMD array
COMPOSE_CMD=()
_COMPOSE_SUDO_WARNED=false
detect_compose_cmd() {
if docker info &>/dev/null; then
COMPOSE_CMD=(docker compose)
else
if [[ "$_COMPOSE_SUDO_WARNED" != "true" ]]; then
log_warn "Docker socket not accessible in current shell — using sudo."
_COMPOSE_SUDO_WARNED=true
fi
COMPOSE_CMD=(sudo docker compose)
fi
}
# Run a docker compose command with correct env-file and compose-file
compose_cmd() {
if [[ ${#COMPOSE_CMD[@]} -eq 0 ]]; then
detect_compose_cmd
fi
# CD into directory so Docker auto-discovers both docker-compose.yml and docker-compose.override.yml
(cd "${INSTALL_DIR}" && exec "${COMPOSE_CMD[@]}" --env-file "${ENV_FILE}" "$@")
}
# ============================================================================
# Dependency Checks
# ============================================================================
check_dependencies() {
log_section "Checking Dependencies"
local missing=()
if ! command -v docker &>/dev/null; then
missing+=("docker")
fi
if docker compose version &>/dev/null; then
log_info "Docker Compose: using v2 plugin (docker compose)."
else
missing+=("docker-compose")
fi
if ! command -v curl &>/dev/null; then
missing+=("curl")
fi
if ! command -v jq &>/dev/null; then
missing+=("jq")
fi
if ! command -v openssl &>/dev/null; then
missing+=("openssl")
fi
# timedatectl is optional — only used to auto-detect the host's timezone.
# On non-systemd systems we fall back to TZ=UTC (or the host's $TZ env var).
if ! command -v timedatectl &>/dev/null; then
log_warn "timedatectl not found; will default timezone to \${TZ:-UTC}."
fi
if [[ ${#missing[@]} -gt 0 ]]; then
log_warn "Missing dependencies: ${missing[*]}"
echo ""
local install_deps="y"
if [[ "$NON_INTERACTIVE" != "true" ]]; then
read -rp "Install missing dependencies automatically? [Y/n]: " install_deps
fi
if [[ "${install_deps,,}" != "n" ]]; then
install_dependencies "${missing[@]}"
else
log_error "Cannot continue without: ${missing[*]}"
exit 1
fi
else
log_info "All dependencies satisfied."
fi
# Ensure docker daemon is running (distinguish permission errors from daemon-down)
if ! docker info &>/dev/null; then
if systemctl is-active --quiet docker 2>/dev/null; then
log_warn "Docker is running but current user lacks permission."
else
log_warn "Docker daemon is not running. Starting it..."
sudo systemctl start docker 2>/dev/null || true
sudo systemctl enable docker 2>/dev/null || true
# Wait for Docker daemon to be ready (up to 15 seconds)
local docker_wait=0
local spin_chars='⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
while [[ $docker_wait -lt 15 ]]; do
if sudo docker info &>/dev/null; then
printf "\r %-50s\r" ""
break
fi
printf "\r %s Waiting for Docker daemon... %ds/15s" "${spin_chars:docker_wait%${#spin_chars}:1}" "$docker_wait"
sleep 1
docker_wait=$((docker_wait + 1))
done
printf "\r %-50s\r" ""
fi
if ! sudo docker info &>/dev/null; then
log_error "Failed to connect to Docker. Please start Docker manually and re-run."
exit 1
fi
fi
# Ensure current user is in docker group (skip if running as root)
if [[ $EUID -ne 0 ]] && ! groups | grep -qw docker; then
log_warn "Current user is not in the 'docker' group."
sudo usermod -aG docker "$USER"
log_warn "Added $USER to docker group. You may need to log out and back in."
log_warn "For now, commands will use sudo as needed."
fi
# Check FUSE support
if [[ ! -e /dev/fuse ]]; then
log_warn "/dev/fuse not found. Loading fuse module..."
sudo modprobe fuse 2>/dev/null || true
if [[ ! -e /dev/fuse ]]; then
log_error "/dev/fuse still not available. Please install FUSE for your distro:"
echo " Arch/CachyOS: sudo pacman -S fuse3"
echo " Debian/Ubuntu: sudo apt install fuse3"
echo " Fedora: sudo dnf install fuse3"
exit 1
fi
fi
log_info "FUSE support available."
}
check_port_conflicts() {
local ports_to_check=() port_names=() svc
for svc in "${SVC_ORDER[@]}"; do
ports_to_check+=("${SVC_PORTS[$svc]}")
port_names+=("${SVC_LABELS[$svc]}")
done
# Add media-server-specific ports if MEDIA_SERVER is already set
if [[ "${MEDIA_SERVER:-}" == "plex" ]]; then
ports_to_check+=(32400)
port_names+=("Plex")
elif [[ "${MEDIA_SERVER:-}" == "jellyfin" ]]; then
ports_to_check+=(8096)
port_names+=("Jellyfin")
fi
local conflicts=false
local network_stats=""
if command -v ss &>/dev/null; then
network_stats=$(ss -tlnp 2>/dev/null)
elif command -v netstat &>/dev/null; then
network_stats=$(netstat -tlnp 2>/dev/null)
fi
for i in "${!ports_to_check[@]}"; do
local port_in_use=false
# Use explicit word-boundary match to avoid partial port matches (e.g., 828 matching 8282)
if echo "$network_stats" | grep -qE ":${ports_to_check[$i]}($|[[:space:]])"; then
port_in_use=true
fi
if [[ "$port_in_use" == "true" ]]; then
log_warn "Port ${ports_to_check[$i]} (${port_names[$i]}) is already in use."
conflicts=true
fi
done
if [[ "$conflicts" == "true" ]]; then
log_warn "Some ports are in use. Services using those ports may fail to start."
log_warn "Stop the conflicting processes or change the ports in docker-compose.yml after setup."
if [[ "$NON_INTERACTIVE" == "true" ]]; then
log_warn "Non-interactive mode: continuing despite port conflicts."
else
read -rp "Continue anyway? [Y/n]: " continue_anyway
if [[ "${continue_anyway,,}" == "n" ]]; then
log_error "Setup cancelled. Free the conflicting ports and re-run."
exit 1
fi
fi
fi
}
install_dependencies() {
local deps=("$@")
log_step "Installing: ${deps[*]}"
# Detect package manager (CachyOS is Arch-based)
if command -v pacman &>/dev/null; then
for dep in "${deps[@]}"; do
case "$dep" in
docker)
sudo pacman -S --noconfirm docker docker-compose-plugin
sudo systemctl enable --now docker
sudo usermod -aG docker "$USER"
;;
docker-compose)
sudo pacman -S --noconfirm docker-compose-plugin
;;
curl)
sudo pacman -S --noconfirm curl
;;
jq)
sudo pacman -S --noconfirm jq
;;
openssl)
sudo pacman -S --noconfirm openssl
;;
esac
done
elif command -v apt-get &>/dev/null; then
sudo apt-get update
for dep in "${deps[@]}"; do
case "$dep" in
docker)
sudo apt-get install -y docker.io docker-compose-plugin
sudo systemctl enable --now docker
sudo usermod -aG docker "$USER"
;;
docker-compose)
sudo apt-get install -y docker-compose-plugin
;;
curl)
sudo apt-get install -y curl
;;
jq)
sudo apt-get install -y jq
;;
openssl)
sudo apt-get install -y openssl
;;
esac
done
elif command -v dnf &>/dev/null; then
for dep in "${deps[@]}"; do
case "$dep" in
docker)
# Use the Compose v2 plugin — the legacy `docker-compose` (v1, Python) was deprecated July 2023.
sudo dnf install -y docker docker-compose-plugin
sudo systemctl enable --now docker
sudo usermod -aG docker "$USER"
;;
docker-compose)
sudo dnf install -y docker-compose-plugin
;;
curl)
sudo dnf install -y curl
;;
jq)
sudo dnf install -y jq
;;
openssl)
sudo dnf install -y openssl
;;
esac
done
else
log_error "Unsupported package manager. Please install ${deps[*]} manually."
exit 1
fi
log_info "Dependencies installed."
}
# ============================================================================
# User Configuration
# ============================================================================
gather_config() {
log_section "Configuration"
# TorBox API Key
echo -e "${BOLD}TorBox API Key${NC}"
echo " Get your API key from: https://torbox.app/settings"
echo ""
if [[ -n "${TORBOX_API_KEY:-}" ]]; then
# Non-interactive: use env var
log_info "Using TorBox API key from TORBOX_API_KEY env var."
elif [[ -n "${EXISTING_TORBOX_API_KEY:-}" ]]; then
echo -e " ${GREEN}Previous API key found.${NC} Press Enter to keep it, or paste a new one."
read -rsp " TorBox API key [keep existing]: " new_torbox_key
echo ""
if [[ -n "$new_torbox_key" ]]; then
TORBOX_API_KEY="$new_torbox_key"
else
TORBOX_API_KEY="$EXISTING_TORBOX_API_KEY"
log_info "Keeping existing TorBox API key."
fi
else
while true; do
read -rsp " Enter your TorBox API key: " TORBOX_API_KEY
echo ""
if [[ -n "$TORBOX_API_KEY" ]]; then
break
fi
log_error "API key cannot be empty."
done
fi
TORBOX_API_KEY="${TORBOX_API_KEY:-${EXISTING_TORBOX_API_KEY:-}}"
# Validate API key with allowlist — only safe characters permitted
if [[ ! "$TORBOX_API_KEY" =~ ^[a-zA-Z0-9._-]+$ ]]; then
log_error "API key contains invalid characters. Only alphanumeric characters, dots, hyphens, and underscores are allowed."
log_error "Please copy it directly from https://torbox.app/settings"
exit 1
fi
log_info "API key received (${#TORBOX_API_KEY} characters, ending in ...${TORBOX_API_KEY: -4})."
# Best-effort live verification against the TorBox API (non-fatal — works offline too).
if command -v curl &>/dev/null; then
local _torbox_check_status
_torbox_check_status=$(curl -s -o /dev/null -w '%{http_code}' \
--connect-timeout 5 --max-time 10 \
-H "Authorization: Bearer ${TORBOX_API_KEY}" \
"https://api.torbox.app/v1/api/user/me" 2>/dev/null) || _torbox_check_status="000"
case "$_torbox_check_status" in
200) log_info "TorBox API key verified against api.torbox.app." ;;
401 | 403)
log_error "TorBox API rejected this key (HTTP ${_torbox_check_status}). Double-check it at https://torbox.app/settings."
if [[ "$NON_INTERACTIVE" != "true" ]]; then
read -rp "Continue with this key anyway? [y/N]: " _cont
[[ "${_cont,,}" != "y" ]] && exit 1
else
exit 1
fi
;;
000 | "") log_warn "Could not reach api.torbox.app to verify the key (offline?). Continuing." ;;
*) log_warn "Unexpected response from TorBox API (HTTP ${_torbox_check_status}). Continuing." ;;
esac
fi
echo ""
# Media Server Choice
echo -e "${BOLD}Media Server${NC}"
if [[ -n "${TORBOX_MEDIA_SERVER:-}" ]]; then
MEDIA_SERVER="${TORBOX_MEDIA_SERVER}"
log_info "Using media server from TORBOX_MEDIA_SERVER env var: ${MEDIA_SERVER}"
elif [[ -n "${EXISTING_COMPOSE_PROFILES:-}" ]]; then
MEDIA_SERVER="${EXISTING_COMPOSE_PROFILES}"
log_info "Keeping existing media server: ${MEDIA_SERVER}"
elif [[ "$NON_INTERACTIVE" == "true" ]]; then
MEDIA_SERVER="plex"
log_info "Non-interactive mode: defaulting to Plex."
else
echo " 1) Plex"
echo " 2) Jellyfin"
echo ""
while true; do
read -rp " Choose your media server [1/2]: " media_choice
case "$media_choice" in
1)
MEDIA_SERVER="plex"
break
;;
2)
MEDIA_SERVER="jellyfin"
break
;;
*) log_error "Please enter 1 or 2." ;;
esac
done
fi
# Validate media server choice
if [[ "$MEDIA_SERVER" != "plex" && "$MEDIA_SERVER" != "jellyfin" ]]; then
log_warn "Invalid media server '${MEDIA_SERVER}'. Defaulting to plex."
MEDIA_SERVER="plex"
fi
PLEX_CLAIM="${TORBOX_PLEX_CLAIM:-}"
if [[ "$MEDIA_SERVER" == "plex" && -z "$PLEX_CLAIM" && "$NON_INTERACTIVE" != "true" ]]; then
echo ""
echo -e "${BOLD}Plex Claim Token${NC} (optional, for first-time setup)"
echo " Get your claim token from: https://www.plex.tv/claim/"
echo " Press Enter to skip."
read -rp " Plex claim token: " PLEX_CLAIM
PLEX_CLAIM="${PLEX_CLAIM:-}"
fi
if [[ -n "$PLEX_CLAIM" && ! "$PLEX_CLAIM" =~ ^claim-[a-zA-Z0-9_-]+$ ]]; then
log_error "Invalid Plex claim token format. Tokens start with 'claim-' followed by alphanumeric characters."
log_error "Please copy it directly from https://www.plex.tv/claim/"
exit 1
fi
echo ""
# Mount directory — use default silently, allow override via env var
MOUNT_DIR="${TORBOX_MOUNT_DIR:-/mnt/torbox-media}"
if [[ "$NON_INTERACTIVE" != "true" && -z "${TORBOX_MOUNT_DIR:-}" ]]; then
echo -e "${BOLD}Mount Directory${NC} [${MOUNT_DIR}]:"
read -rp " Press Enter to accept, or type a custom path: " custom_mount
MOUNT_DIR="${custom_mount:-$MOUNT_DIR}"
fi
if [[ "$MOUNT_DIR" != /* ]]; then
log_error "Mount path must be an absolute path (start with /). Using default."
MOUNT_DIR="/mnt/torbox-media"
fi
# Block system directory prefixes
for prefix in /etc /usr /var /tmp /proc /sys /dev /boot /sbin /bin /lib /run; do
if [[ "$MOUNT_DIR" == "$prefix" || "$MOUNT_DIR" == "$prefix"/* ]]; then
log_error "'${MOUNT_DIR}' is under a system directory. Using default."
MOUNT_DIR="/mnt/torbox-media"
break
fi
done
# Reject unsafe characters in mount path
if [[ "$MOUNT_DIR" =~ [^a-zA-Z0-9_./-] ]]; then
log_error "Mount path contains unsafe characters. Using default."
MOUNT_DIR="/mnt/torbox-media"
fi
# Reject mount paths that are inside the installation directory — this would
# cause recursive shared mounts (Decypharr's FUSE mount would itself be visible
# under INSTALL_DIR/configs, leading to mount loops and `rm -rf` data loss
# during uninstall).
if [[ "$MOUNT_DIR" == "$INSTALL_DIR" || "$MOUNT_DIR" == "$INSTALL_DIR"/* ]]; then
log_error "Mount path '${MOUNT_DIR}' is inside the install directory '${INSTALL_DIR}'."
log_error "This would cause recursive mounts and data loss. Using default."
MOUNT_DIR="/mnt/torbox-media"
fi
echo ""
# User/Group IDs
PUID="$(id -u)"
PGID="$(id -g)"
echo -e "${BOLD}User/Group IDs${NC}"
echo " Detected: PUID=${PUID}, PGID=${PGID}"
if [[ "$NON_INTERACTIVE" != "true" ]]; then
read -rp " Use these? [Y/n]: " use_ids
if [[ "${use_ids,,}" == "n" ]]; then
while true; do
read -rp " PUID: " PUID
read -rp " PGID: " PGID
if [[ "$PUID" =~ ^[0-9]+$ && "$PGID" =~ ^[0-9]+$ ]]; then
break
fi
log_error "PUID and PGID must be numeric values."
done
fi
fi
# Timezone — prefer timedatectl, then $TZ, then /etc/timezone, finally UTC.
if command -v timedatectl &>/dev/null; then
TZ="$(timedatectl show -p Timezone --value 2>/dev/null || echo '')"
fi
if [[ -z "${TZ:-}" && -r /etc/timezone ]]; then
TZ="$(tr -d '[:space:]' </etc/timezone)"
fi
TZ="${TZ:-UTC}"
echo ""
echo -e "${BOLD}Timezone${NC}: ${TZ}"
if [[ "$NON_INTERACTIVE" != "true" ]]; then
read -rp " Use this timezone? [Y/n]: " use_tz
if [[ "${use_tz,,}" == "n" ]]; then
while true; do
read -rp " Enter timezone (e.g., America/New_York): " TZ
if command -v timedatectl &>/dev/null && timedatectl list-timezones 2>/dev/null | grep -qx "$TZ"; then
break
elif [[ "$TZ" =~ ^[a-zA-Z_/+-]+$ ]]; then
log_warn "Could not verify timezone '$TZ' against system list. Using it anyway."
break
else
log_error "Invalid timezone format. Use format like 'America/New_York' or 'UTC'."
fi
done
fi
fi
# Generate or preserve API keys for the *arr services
if [[ -n "${EXISTING_RADARR_API_KEY:-}" && -n "${EXISTING_SONARR_API_KEY:-}" && -n "${EXISTING_PROWLARR_API_KEY:-}" ]]; then
RADARR_API_KEY="$EXISTING_RADARR_API_KEY"
SONARR_API_KEY="$EXISTING_SONARR_API_KEY"
PROWLARR_API_KEY="$EXISTING_PROWLARR_API_KEY"
log_info "Preserved existing API keys from previous installation."
else
RADARR_API_KEY="$(generate_api_key)"
SONARR_API_KEY="$(generate_api_key)"
PROWLARR_API_KEY="$(generate_api_key)"
# Validate keys are non-empty and correct length
for key_name in RADARR_API_KEY SONARR_API_KEY PROWLARR_API_KEY; do
local key_val="${!key_name}"
if [[ -z "$key_val" || ${#key_val} -lt 32 ]]; then
log_error "Failed to generate API key for ${key_name}. Ensure openssl, xxd, or od is installed."
exit 1
fi
done
fi
# Generate or preserve admin credentials for the *arr services
# Radarr
if [[ -n "${EXISTING_RADARR_ADMIN_USER:-}" && -n "${EXISTING_RADARR_ADMIN_PASS:-}" ]]; then
RADARR_ADMIN_USER="$EXISTING_RADARR_ADMIN_USER"
RADARR_ADMIN_PASS="$EXISTING_RADARR_ADMIN_PASS"
else
RADARR_ADMIN_USER="admin"
RADARR_ADMIN_PASS="$(_gen_admin_pass)"
fi
# Sonarr
if [[ -n "${EXISTING_SONARR_ADMIN_USER:-}" && -n "${EXISTING_SONARR_ADMIN_PASS:-}" ]]; then
SONARR_ADMIN_USER="$EXISTING_SONARR_ADMIN_USER"
SONARR_ADMIN_PASS="$EXISTING_SONARR_ADMIN_PASS"
else
SONARR_ADMIN_USER="admin"
SONARR_ADMIN_PASS="$(_gen_admin_pass)"
fi
# Prowlarr
if [[ -n "${EXISTING_PROWLARR_ADMIN_USER:-}" && -n "${EXISTING_PROWLARR_ADMIN_PASS:-}" ]]; then
PROWLARR_ADMIN_USER="$EXISTING_PROWLARR_ADMIN_USER"
PROWLARR_ADMIN_PASS="$EXISTING_PROWLARR_ADMIN_PASS"
else
PROWLARR_ADMIN_USER="admin"
PROWLARR_ADMIN_PASS="$(_gen_admin_pass)"
fi
# Validate passwords are non-empty
for key_name in RADARR_ADMIN_PASS SONARR_ADMIN_PASS PROWLARR_ADMIN_PASS; do
if [[ -z "${!key_name}" ]]; then
log_error "Failed to generate admin password for ${key_name}. Ensure openssl or /dev/urandom is available."
exit 1
fi
done
echo ""
# Hardware Acceleration — auto-detect, then prompt only if ambiguous
echo -e "${BOLD}Hardware Acceleration${NC}"
if [[ -n "${TORBOX_HW_ACCEL:-}" ]]; then
HW_ACCEL="${TORBOX_HW_ACCEL}"
log_info "Using hardware acceleration from TORBOX_HW_ACCEL env var: ${HW_ACCEL}"
else
local detected_intel=false detected_amd=false detected_nvidia=false
# Distinguish Intel vs AMD GPUs by inspecting the render-node driver / PCI vendor.
# /dev/dri alone is not enough — both vendors expose it.
if [[ -d /dev/dri ]]; then
local _gpu_vendors=""
if command -v lspci &>/dev/null; then
# Use PCI class codes 0300 (VGA) and 0302 (3D controller) to
# avoid false positives — a naive text grep on "3d" matches
# hex IDs like [8086:a33d] in PCIe root port lines.
_gpu_vendors=$( (
lspci -d ::0300 -nn 2>/dev/null
lspci -d ::0302 -nn 2>/dev/null
) || true)
fi
if [[ -n "$_gpu_vendors" ]]; then
# Vendor IDs: Intel=8086, AMD=1002/1022, NVIDIA=10de
echo "$_gpu_vendors" | grep -qE '\[8086:' && detected_intel=true
echo "$_gpu_vendors" | grep -qE '\[1002:|\[1022:' && detected_amd=true
echo "$_gpu_vendors" | grep -qiE 'nvidia|\[10de:' && detected_nvidia=true
else
# lspci not available — fall back to inspecting render-node driver symlinks
if find /dev/dri/by-path -maxdepth 1 -name '*render*' -ls 2>/dev/null | grep -qiE 'amdgpu|radeon'; then
detected_amd=true
elif find /dev/dri/by-path -maxdepth 1 -name '*render*' -ls 2>/dev/null | grep -qiE 'i915|xe'; then
detected_intel=true
else
# No way to disambiguate — assume Intel (most common integrated GPU)
# but warn the user so they can override.
detected_intel=true
log_warn "Could not identify /dev/dri GPU vendor (lspci unavailable). Assuming Intel."
fi
fi
fi
if command -v nvidia-smi &>/dev/null || [[ -e /dev/nvidia0 ]]; then
detected_nvidia=true
fi
local _gpu_count=0
[[ "$detected_intel" == "true" ]] && _gpu_count=$((_gpu_count + 1))
[[ "$detected_amd" == "true" ]] && _gpu_count=$((_gpu_count + 1))
[[ "$detected_nvidia" == "true" ]] && _gpu_count=$((_gpu_count + 1))
if [[ $_gpu_count -eq 1 ]]; then
if [[ "$detected_intel" == "true" ]]; then
HW_ACCEL="intel"
log_info "Auto-detected Intel QuickSync (/dev/dri)."
elif [[ "$detected_amd" == "true" ]]; then
HW_ACCEL="amd"
log_info "Auto-detected AMD GPU (VAAPI)."
else
HW_ACCEL="nvidia"
log_info "Auto-detected NVIDIA GPU."
fi
elif [[ $_gpu_count -gt 1 ]]; then
if [[ "$NON_INTERACTIVE" == "true" ]]; then
# Prefer integrated GPU (power-efficient) when multiple are present
if [[ "$detected_intel" == "true" ]]; then
HW_ACCEL="intel"
elif [[ "$detected_amd" == "true" ]]; then
HW_ACCEL="amd"
else
HW_ACCEL="nvidia"
fi
log_info "Multiple GPUs detected. Non-interactive: defaulting to ${HW_ACCEL}."
else
echo " Multiple GPUs detected:"
[[ "$detected_intel" == "true" ]] && echo " • Intel QuickSync"
[[ "$detected_amd" == "true" ]] && echo " • AMD VAAPI"
[[ "$detected_nvidia" == "true" ]] && echo " • NVIDIA NVENC (requires nvidia-container-toolkit)"
echo ""
local opts=() i=1
[[ "$detected_intel" == "true" ]] && {
echo " $i) Intel QuickSync"
opts+=("intel")
i=$((i + 1))
}
[[ "$detected_amd" == "true" ]] && {
echo " $i) AMD VAAPI"
opts+=("amd")
i=$((i + 1))
}
[[ "$detected_nvidia" == "true" ]] && {
echo " $i) NVIDIA NVENC"
opts+=("nvidia")
i=$((i + 1))
}
echo ""
while true; do
read -rp " Choose hardware acceleration [1-$((i - 1))]: " hw_choice
if [[ "$hw_choice" =~ ^[0-9]+$ ]] && ((hw_choice >= 1 && hw_choice < i)); then
HW_ACCEL="${opts[$((hw_choice - 1))]}"
break
fi
log_error "Please enter a number between 1 and $((i - 1))."
done
fi
else
if [[ "$NON_INTERACTIVE" == "true" ]]; then
HW_ACCEL="none"
log_info "No GPU detected. Non-interactive: using software transcoding."
else
echo " No GPU detected."
echo " 1) None (software transcoding only)"
echo " 2) Intel QuickSync (if you have integrated GPU)"
echo " 3) AMD VAAPI (if you have an AMD GPU)"
echo " 4) NVIDIA NVENC (if you have discrete NVIDIA GPU)"
echo ""
while true; do
read -rp " Choose hardware acceleration [1/2/3/4]: " hw_choice
case "$hw_choice" in
1)
HW_ACCEL="none"
break
;;
2)
HW_ACCEL="intel"
break
;;
3)
HW_ACCEL="amd"
break
;;
4)
HW_ACCEL="nvidia"
break
;;
*) log_error "Please enter 1, 2, 3, or 4." ;;
esac
done
fi
fi
fi
# Verify nvidia-container-toolkit is installed if NVIDIA is selected.
# Try to auto-install it using the detected package manager.
if [[ "${HW_ACCEL}" == "nvidia" ]]; then
local _has_nvidia_toolkit=false
command -v nvidia-container-runtime &>/dev/null && _has_nvidia_toolkit=true
dpkg -s nvidia-container-toolkit &>/dev/null 2>&1 && _has_nvidia_toolkit=true
rpm -q nvidia-container-toolkit &>/dev/null 2>&1 && _has_nvidia_toolkit=true
pacman -Qi nvidia-container-toolkit &>/dev/null 2>&1 && _has_nvidia_toolkit=true
if [[ "$_has_nvidia_toolkit" == "false" ]]; then
log_warn "nvidia-container-toolkit is not installed. Attempting to install..."
local _install_ok=false
if command -v pacman &>/dev/null; then
sudo pacman -S --noconfirm nvidia-container-toolkit && _install_ok=true
elif command -v apt-get &>/dev/null; then
sudo apt-get update -qq && sudo apt-get install -y nvidia-container-toolkit && _install_ok=true
elif command -v dnf &>/dev/null; then
sudo dnf install -y nvidia-container-toolkit && _install_ok=true
else
log_error "Could not auto-install nvidia-container-toolkit (unknown package manager)."
fi
if [[ "$_install_ok" == "true" ]]; then
log_info "nvidia-container-toolkit installed successfully."
# Configure Docker to use the nvidia runtime and restart
log_step "Configuring Docker for NVIDIA GPU..."
if sudo nvidia-ctk runtime configure --runtime=docker 2>/dev/null; then
sudo systemctl restart docker 2>/dev/null || true
# Wait for Docker daemon to be ready
local _docker_wait=0
while [[ $_docker_wait -lt 15 ]]; do
if docker info &>/dev/null; then
break
fi
sleep 1
_docker_wait=$((_docker_wait + 1))
done
if docker info &>/dev/null; then
log_info "Docker restarted with NVIDIA runtime."
else
log_warn "Docker restarted but may not be ready. You may need to restart Docker manually."
fi
else
log_warn "nvidia-ctk runtime configure failed. NVIDIA GPU may not work in containers."
log_warn "Try: sudo nvidia-ctk runtime configure --runtime=docker && sudo systemctl restart docker"
fi
else
log_error "nvidia-container-toolkit installation failed."
log_error "Install it manually, then re-run setup.sh."
echo ""
echo " Arch/CachyOS: sudo pacman -S nvidia-container-toolkit"
echo " Debian/Ubuntu: sudo apt install nvidia-container-toolkit"
echo " Fedora: sudo dnf install nvidia-container-toolkit"
echo ""
log_info "Falling back to software transcoding."
HW_ACCEL="none"
fi
else
log_info "nvidia-container-toolkit is installed."
fi
fi
echo ""
log_info "Configuration complete."
log_info "Generated API keys for Radarr, Sonarr, and Prowlarr."
# Show confirmation summary
log_section "Configuration Summary"
echo -e " ${BOLD}TorBox API Key:${NC} ...${TORBOX_API_KEY: -4}"
echo -e " ${BOLD}Media Server:${NC} ${MEDIA_SERVER}"
echo -e " ${BOLD}Mount Directory:${NC} ${MOUNT_DIR}"
echo -e " ${BOLD}PUID/PGID:${NC} ${PUID}:${PGID}"
echo -e " ${BOLD}Timezone:${NC} ${TZ}"
echo -e " ${BOLD}HW Acceleration:${NC} ${HW_ACCEL}"
echo ""
if [[ "$NON_INTERACTIVE" != "true" ]]; then
read -rp "Proceed with these settings? [Y/n]: " confirm_config
if [[ "${confirm_config,,}" == "n" ]]; then
log_info "Setup cancelled."
exit 0
fi
fi
}
# ============================================================================
# Directory Structure
# ============================================================================
create_directories() {
log_section "Creating Directory Structure"
# Directories need more permissive permissions for container access
local saved_umask
saved_umask="$(umask)"
umask 022
mkdir -p "${INSTALL_DIR}"
mkdir -p "${CONFIG_DIR}"/{prowlarr,radarr,sonarr,seerr,decypharr}
mkdir -p "${DATA_DIR}"/{media/{movies,tv},downloads/{radarr,sonarr}}
if [[ "$MEDIA_SERVER" == "plex" ]]; then
mkdir -p "${CONFIG_DIR}/plex"
else
mkdir -p "${CONFIG_DIR}/jellyfin"
fi
# Restore restrictive umask for subsequent file creation
umask "$saved_umask"
# Create mount point
sudo mkdir -p "${MOUNT_DIR}"
sudo chown "${PUID}:${PGID}" "${MOUNT_DIR}"
# Ensure mount point supports shared propagation for rclone FUSE mounts
log_step "Setting up mount propagation..."
if ! findmnt -n "${MOUNT_DIR}" &>/dev/null; then
sudo mount --bind "${MOUNT_DIR}" "${MOUNT_DIR}" 2>/dev/null || true
fi
sudo mount --make-shared "${MOUNT_DIR}" 2>/dev/null || true
if findmnt -n -o PROPAGATION "${MOUNT_DIR}" 2>/dev/null | grep -q "shared"; then
log_info "Mount propagation configured (shared)."
else
log_warn "Mount propagation may not be active. Decypharr's FUSE mounts might not be visible to other containers."
log_warn "If media files aren't visible in Plex/Jellyfin, see the troubleshooting section in README."
fi
log_info "Directories created at: ${INSTALL_DIR}"
}
# ============================================================================
# Generate Decypharr Config
# ============================================================================
generate_decypharr_config() {
log_step "Generating Decypharr configuration..."
if [[ -f "${CONFIG_DIR}/decypharr/config.json" ]]; then
log_info "Decypharr config already exists. Preserving user customizations."
return 0
fi
# Generate credentials for Decypharr web UI
DECYPHARR_USER="${DECYPHARR_USER:-torbox}"
if [[ -z "${DECYPHARR_PASS:-}" ]]; then
DECYPHARR_PASS="$(openssl rand -base64 12 2>/dev/null | tr -d '/+=' | head -c 12)"
if [[ -z "$DECYPHARR_PASS" ]]; then
DECYPHARR_PASS="$(head -c 12 /dev/urandom | base64 | tr -d '/+=' | head -c 12)"
fi
fi
cat >"${CONFIG_DIR}/decypharr/config.json" <<DECYPHARR_EOF
{
"debrids": [
{
"name": "torbox",