-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.sh
More file actions
executable file
·2601 lines (2360 loc) · 109 KB
/
setup.sh
File metadata and controls
executable file
·2601 lines (2360 loc) · 109 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
# ============================================================================
# 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
trap 'cleanup_on_interrupt' INT TERM
cleanup_on_interrupt() {
echo ""
# 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"
}
# 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)
"$@" > "$tmpfile" 2>&1 &
local pid=$! i=0
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"
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}" && "${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
if ! command -v timedatectl &>/dev/null; then
missing+=("timedatectl")
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 8920)
port_names+=("Jellyfin" "Jellyfin HTTPS")
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
;;
timedatectl)
sudo pacman -S --noconfirm systemd
;;
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
;;
timedatectl)
sudo apt-get install -y systemd
;;
esac
done
elif command -v dnf &>/dev/null; then
for dep in "${deps[@]}"; do
case "$dep" in
docker)
sudo dnf install -y docker docker-compose
sudo systemctl enable --now docker
sudo usermod -aG docker "$USER"
;;
docker-compose)
sudo dnf install -y docker-compose
;;
curl)
sudo dnf install -y curl
;;
jq)
sudo dnf install -y jq
;;
openssl)
sudo dnf install -y openssl
;;
timedatectl)
sudo dnf install -y systemd-udev
;;
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})."
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
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
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
TZ="$(timedatectl show -p Timezone --value 2>/dev/null || echo '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 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
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_nvidia=false
if [[ -d /dev/dri ]]; then
detected_intel=true
fi
if command -v nvidia-smi &>/dev/null || [[ -e /dev/nvidia0 ]]; then
detected_nvidia=true
fi
if [[ "$detected_intel" == "true" && "$detected_nvidia" == "false" ]]; then
HW_ACCEL="intel"
log_info "Auto-detected Intel QuickSync (/dev/dri)."
elif [[ "$detected_nvidia" == "true" && "$detected_intel" == "false" ]]; then
HW_ACCEL="nvidia"
log_info "Auto-detected NVIDIA GPU."
elif [[ "$detected_intel" == "true" && "$detected_nvidia" == "true" ]]; then
if [[ "$NON_INTERACTIVE" == "true" ]]; then
HW_ACCEL="intel"
log_info "Both GPUs detected. Non-interactive: defaulting to Intel QuickSync."
else
echo " Both Intel and NVIDIA GPUs detected."
echo " 1) Intel QuickSync (recommended - uses integrated GPU, power-efficient)"
echo " 2) NVIDIA NVENC (uses discrete GPU, requires nvidia-container-toolkit)"
echo ""
while true; do
read -rp " Choose hardware acceleration [1/2]: " hw_choice
case "$hw_choice" in
1) HW_ACCEL="intel"; break ;;
2) HW_ACCEL="nvidia"; break ;;
*) log_error "Please enter 1 or 2." ;;
esac
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) NVIDIA NVENC (if you have discrete GPU)"
echo ""
while true; do
read -rp " Choose hardware acceleration [1/2/3]: " hw_choice
case "$hw_choice" in
1) HW_ACCEL="none"; break ;;
2) HW_ACCEL="intel"; break ;;
3) HW_ACCEL="nvidia"; break ;;
*) log_error "Please enter 1, 2, or 3." ;;
esac
done
fi
fi
fi
# Verify nvidia-container-toolkit is installed if NVIDIA is selected
if [[ "${HW_ACCEL}" == "nvidia" ]]; then
if ! command -v nvidia-container-runtime &>/dev/null && \
! dpkg -l nvidia-container-toolkit &>/dev/null && \
! rpm -q nvidia-container-toolkit &>/dev/null && \
! pacman -Qi nvidia-container-toolkit &>/dev/null; then
log_error "NVIDIA GPU detected but nvidia-container-toolkit is not installed."
log_error "Docker cannot use NVIDIA GPUs without the container toolkit."
echo ""
echo " Install it with:"
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"
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="torbox"
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
cat > "${CONFIG_DIR}/decypharr/config.json" << DECYPHARR_EOF
{
"debrids": [
{
"name": "torbox",
"api_key": "${TORBOX_API_KEY}",
"folder": "/mnt/remote/torbox/__all__",
"rate_limit": "55/hour",
"use_webdav": true
}
],
"rclone": {
"enabled": true,
"mount_path": "/mnt/remote"
},
"qbittorrent": {
"download_folder": "/data/downloads/",
"categories": ["sonarr", "radarr"]
},
"username": "${DECYPHARR_USER}",
"password": "${DECYPHARR_PASS}",
"port": "8282",
"log_level": "info"
}
DECYPHARR_EOF
chmod 600 "${CONFIG_DIR}/decypharr/config.json"
log_info "Decypharr config written with pre-seeded credentials."
}
# ============================================================================
# Generate *arr Config XML (Pre-seed API keys & auth)
# ============================================================================
generate_arr_configs() {
log_step "Pre-seeding Radarr, Sonarr, and Prowlarr configs..."
# On re-run, only update the ApiKey line to preserve user settings
local arr_name arr_dir arr_key
for arr_name in radarr sonarr prowlarr; do
arr_dir="${CONFIG_DIR}/${arr_name}/config.xml"
case "$arr_name" in
radarr) arr_key="${RADARR_API_KEY}" ;;
sonarr) arr_key="${SONARR_API_KEY}" ;;
prowlarr) arr_key="${PROWLARR_API_KEY}" ;;
esac
if [[ -f "$arr_dir" ]]; then
# Validate key is pure hex before using in sed replacement
if [[ ! "$arr_key" =~ ^[0-9a-f]{32}$ ]]; then
log_warn " API key for ${arr_name} is not valid hex. Regenerating."
arr_key="$(generate_api_key)"
fi
sed -i "s|<ApiKey>.*</ApiKey>|<ApiKey>${arr_key}</ApiKey>|" "$arr_dir"
log_info " Updated API key in existing ${arr_name} config.xml (other settings preserved)."
fi
done
# Only write fresh config.xml if it doesn't already exist
if [[ ! -f "${CONFIG_DIR}/radarr/config.xml" ]]; then
# --- Radarr config.xml ---
cat > "${CONFIG_DIR}/radarr/config.xml" << RADARR_XML_EOF
<Config>
<LogLevel>info</LogLevel>
<EnableSsl>False</EnableSsl>
<Port>7878</Port>
<SslPort>9898</SslPort>
<UrlBase></UrlBase>
<BindAddress>*</BindAddress>
<ApiKey>${RADARR_API_KEY}</ApiKey>
<AuthenticationMethod>Forms</AuthenticationMethod>
<AuthenticationRequired>DisabledForLocalAddresses</AuthenticationRequired>
<Branch>master</Branch>
<InstanceName>Radarr</InstanceName>
</Config>
RADARR_XML_EOF
chmod 600 "${CONFIG_DIR}/radarr/config.xml"
fi
if [[ ! -f "${CONFIG_DIR}/sonarr/config.xml" ]]; then
# --- Sonarr config.xml ---
cat > "${CONFIG_DIR}/sonarr/config.xml" << SONARR_XML_EOF
<Config>
<LogLevel>info</LogLevel>
<EnableSsl>False</EnableSsl>
<Port>8989</Port>
<SslPort>9898</SslPort>
<UrlBase></UrlBase>
<BindAddress>*</BindAddress>
<ApiKey>${SONARR_API_KEY}</ApiKey>
<AuthenticationMethod>Forms</AuthenticationMethod>
<AuthenticationRequired>DisabledForLocalAddresses</AuthenticationRequired>
<Branch>main</Branch>
<InstanceName>Sonarr</InstanceName>
</Config>
SONARR_XML_EOF
chmod 600 "${CONFIG_DIR}/sonarr/config.xml"
fi
if [[ ! -f "${CONFIG_DIR}/prowlarr/config.xml" ]]; then
# --- Prowlarr config.xml ---
cat > "${CONFIG_DIR}/prowlarr/config.xml" << PROWLARR_XML_EOF
<Config>
<LogLevel>info</LogLevel>
<EnableSsl>False</EnableSsl>
<Port>9696</Port>
<SslPort>6969</SslPort>
<UrlBase></UrlBase>
<BindAddress>*</BindAddress>
<ApiKey>${PROWLARR_API_KEY}</ApiKey>
<AuthenticationMethod>Forms</AuthenticationMethod>
<AuthenticationRequired>DisabledForLocalAddresses</AuthenticationRequired>
<Branch>develop</Branch>
<InstanceName>Prowlarr</InstanceName>
</Config>
PROWLARR_XML_EOF
chmod 600 "${CONFIG_DIR}/prowlarr/config.xml"
fi
log_info "Pre-seeded config.xml for Radarr, Sonarr, and Prowlarr."
log_info " Radarr API key: $(mask_key "${RADARR_API_KEY}")"
log_info " Sonarr API key: $(mask_key "${SONARR_API_KEY}")"
log_info " Prowlarr API key: $(mask_key "${PROWLARR_API_KEY}")"
}
# ============================================================================
# Generate .env File
# ============================================================================
generate_env_file() {
log_step "Generating environment file..."
# Set the compose profile based on media server choice
local compose_profile="plex"
if [[ "${MEDIA_SERVER}" == "jellyfin" ]]; then
compose_profile="jellyfin"
fi
cat > "${ENV_FILE}" << ENV_EOF
# TorBox Media Server - Environment Configuration
# Generated on $(date)
# User/Group IDs (match your host user)
PUID="${PUID}"
PGID="${PGID}"
# Timezone
TZ="${TZ}"
# TorBox
TORBOX_API_KEY="${TORBOX_API_KEY}"
# Paths
CONFIG_DIR="${CONFIG_DIR}"
DATA_DIR="${DATA_DIR}"
MOUNT_DIR="${MOUNT_DIR}"
# Docker Compose Profile (activates only the selected media server)
COMPOSE_PROFILES="${compose_profile}"
# Plex
PLEX_CLAIM="${PLEX_CLAIM:-}"
# *arr API Keys (pre-seeded)
RADARR_API_KEY="${RADARR_API_KEY}"
SONARR_API_KEY="${SONARR_API_KEY}"
PROWLARR_API_KEY="${PROWLARR_API_KEY}"
# Decypharr credentials (pre-seeded)
DECYPHARR_USER="${DECYPHARR_USER:-torbox}"
DECYPHARR_PASS="${DECYPHARR_PASS:-}"
ENV_EOF
# Preserve existing admin credentials if this is a re-run
if [[ -n "${EXISTING_RADARR_ADMIN_USER:-}" ]]; then
cat >> "${ENV_FILE}" << ADMIN_EOF
# Admin Credentials (Preserved)
RADARR_ADMIN_USER="${EXISTING_RADARR_ADMIN_USER}"
RADARR_ADMIN_PASS="${EXISTING_RADARR_ADMIN_PASS}"
SONARR_ADMIN_USER="${EXISTING_SONARR_ADMIN_USER}"
SONARR_ADMIN_PASS="${EXISTING_SONARR_ADMIN_PASS}"
PROWLARR_ADMIN_USER="${EXISTING_PROWLARR_ADMIN_USER}"
PROWLARR_ADMIN_PASS="${EXISTING_PROWLARR_ADMIN_PASS}"
ADMIN_EOF
fi
chmod 600 "${ENV_FILE}"
log_info "Environment file written (profile: ${compose_profile})."
}
# ============================================================================
# Generate Docker Compose
# ============================================================================
generate_docker_compose() {
log_step "Setting up Docker Compose..."
# Copy static compose file from repo to install directory
cp "${SCRIPT_DIR}/docker-compose.yml" "${COMPOSE_FILE}"
# Ensure no ghost overrides remain from previous installations
rm -f "${INSTALL_DIR}/docker-compose.override.yml"
# Generate hardware acceleration override (only if needed)
if [[ "${HW_ACCEL}" == "intel" ]]; then
cat > "${INSTALL_DIR}/docker-compose.override.yml" << 'HW_OVERRIDE'
# Auto-generated: Intel QuickSync hardware acceleration
# Active media server gets /dev/dri passthrough
services:
plex:
devices:
- /dev/dri:/dev/dri
jellyfin:
devices:
- /dev/dri:/dev/dri
HW_OVERRIDE
log_info "Hardware acceleration override: Intel QuickSync (/dev/dri)."
elif [[ "${HW_ACCEL}" == "nvidia" ]]; then
cat > "${INSTALL_DIR}/docker-compose.override.yml" << 'HW_OVERRIDE'
# Auto-generated: NVIDIA GPU hardware acceleration
# Active media server gets GPU passthrough
services:
plex:
environment:
- NVIDIA_VISIBLE_DEVICES=all
- NVIDIA_DRIVER_CAPABILITIES=compute,video,utility
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: 1
capabilities: [gpu]
jellyfin:
environment:
- NVIDIA_VISIBLE_DEVICES=all
- NVIDIA_DRIVER_CAPABILITIES=compute,video,utility
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: 1
capabilities: [gpu]
HW_OVERRIDE
log_info "Hardware acceleration override: NVIDIA GPU."