-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsetup.ps1
More file actions
1153 lines (1026 loc) · 47.3 KB
/
Copy pathsetup.ps1
File metadata and controls
1153 lines (1026 loc) · 47.3 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
<#
.SYNOPSIS
TorBox Media Server - All-in-One Setup Script
Automated setup for a debrid-powered media server using Docker on Windows
.DESCRIPTION
Components: Prowlarr, Byparr, Decypharr, Seerr,
Radarr, Sonarr, rclone/WinFSP mount, Plex or Jellyfin
#>
$Version = "1.1.0"
$DryRun = $false
$ServicesStarted = $false
$NonInteractive = $false
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
$InstallDir = Join-Path $ScriptDir "torbox-media-server"
$ConfigDir = Join-Path $InstallDir "configs"
$DataDir = Join-Path $InstallDir "data"
$MountDir = "C:\torbox-media"
$EnvFile = Join-Path $InstallDir ".env"
$ComposeFile = Join-Path $InstallDir "docker-compose.yml"
$SetupCompleteFile = Join-Path $InstallDir ".setup_complete"
function Write-LogInfo ($Message) { Write-Host "[INFO] $Message" -ForegroundColor Green }
function Write-LogWarn ($Message) { Write-Host "[WARN] $Message" -ForegroundColor Yellow }
function Write-LogError ($Message) { Write-Host "[ERROR] $Message" -ForegroundColor Red }
function Write-LogStep ($Message) { Write-Host "[STEP] $Message" -ForegroundColor Blue }
function Write-LogSection ($Message) {
Write-Host "`n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" -ForegroundColor Cyan
Write-Host " $Message" -ForegroundColor Cyan
Write-Host "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`n" -ForegroundColor Cyan
}
function Invoke-PrintBanner {
Write-Host " ╔══════════════════════════════════════════════════════════════╗" -ForegroundColor Cyan
Write-Host " ║ TorBox Media Server - All-in-One Setup ║" -ForegroundColor Cyan
Write-Host " ║ ║" -ForegroundColor Cyan
Write-Host " ║ Prowlarr · Byparr · Decypharr · Seerr ║" -ForegroundColor Cyan
Write-Host " ║ Radarr · Sonarr · rclone/WinFSP · Plex/Jellyfin ║" -ForegroundColor Cyan
Write-Host " ╚══════════════════════════════════════════════════════════════╝" -ForegroundColor Cyan
}
function New-ApiKey {
$bytes = New-Object Byte[] 16
$rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
$rng.GetBytes($bytes)
return -join ($bytes | ForEach-Object { $_.ToString("x2") })
}
function New-AdminPass {
$bytes = New-Object Byte[] 32
$rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
$rng.GetBytes($bytes)
$pass = [Convert]::ToBase64String($bytes).Replace('/', '').Replace('+', '').Replace('=', '')
if ($pass.Length -gt 32) { $pass = $pass.Substring(0, 32) }
return $pass
}
function Get-MaskedKey ($Key) {
if ($Key.Length -gt 4) {
return "$($Key.Substring(0, 4))...$($Key.Substring($Key.Length - 4))"
}
return $Key
}
# Write a UTF-8 text file WITHOUT a byte-order mark. Windows PowerShell 5.1's
# `Set-Content -Encoding UTF8` prepends a BOM, which corrupts the first .env
# variable for Docker Compose and breaks *arr config.xml parsing.
function Write-TextFile ($Path, $Content) {
$utf8NoBom = New-Object System.Text.UTF8Encoding $false
[System.IO.File]::WriteAllText($Path, $Content, $utf8NoBom)
}
function ConvertTo-IanaTimezone {
# Map a Windows timezone ID (e.g. "Pacific Standard Time") to its IANA
# equivalent (e.g. "America/Los_Angeles"). Linux containers expect IANA
# names — the *arr apps (.NET on Linux) will fall back to UTC or throw if
# given a Windows TZ ID.
param([string]$WindowsTzId)
if ([string]::IsNullOrEmpty($WindowsTzId)) { return "UTC" }
# Use the cross-platform Unicode CLDR mapping that ships with .NET.
# .NET's TimeZoneInfo knows the IANA alias for each Windows zone on Linux/Mac,
# but on Windows PowerShell 5.1 we need a lookup table for the common cases.
$map = @{
'UTC' = 'UTC'
'GMT Standard Time' = 'Europe/London'
'Romance Standard Time' = 'Europe/Paris'
'W. Europe Standard Time' = 'Europe/Berlin'
'Central Europe Standard Time' = 'Europe/Budapest'
'E. Europe Standard Time' = 'Europe/Chisinau'
'Jordan Standard Time' = 'Asia/Amman'
'Middle East Standard Time' = 'Asia/Beirut'
'Egypt Standard Time' = 'Africa/Cairo'
'South Africa Standard Time' = 'Africa/Johannesburg'
'Israel Standard Time' = 'Asia/Jerusalem'
'Arabic Standard Time' = 'Asia/Riyadh'
'Arab Standard Time' = 'Asia/Riyadh'
'Arabian Standard Time' = 'Asia/Dubai'
'Iran Standard Time' = 'Asia/Tehran'
'Pakistan Standard Time' = 'Asia/Karachi'
'India Standard Time' = 'Asia/Kolkata'
'Sri Lanka Standard Time' = 'Asia/Colombo'
'Nepal Standard Time' = 'Asia/Kathmandu'
'Bangladesh Standard Time' = 'Asia/Dhaka'
'SE Asia Standard Time' = 'Asia/Bangkok'
'Singapore Standard Time' = 'Asia/Singapore'
'China Standard Time' = 'Asia/Shanghai'
'Taipei Standard Time' = 'Asia/Taipei'
'Tokyo Standard Time' = 'Asia/Tokyo'
'Korea Standard Time' = 'Asia/Seoul'
'AUS Eastern Standard Time' = 'Australia/Sydney'
'E. Australia Standard Time' = 'Australia/Brisbane'
'Cen. Australia Standard Time' = 'Australia/Adelaide'
'W. Australia Standard Time' = 'Australia/Perth'
'New Zealand Standard Time' = 'Pacific/Auckland'
'Hawaiian Standard Time' = 'Pacific/Honolulu'
'Alaskan Standard Time' = 'America/Anchorage'
'Pacific Standard Time' = 'America/Los_Angeles'
'US Mountain Standard Time' = 'America/Phoenix'
'Mountain Standard Time' = 'America/Denver'
'Central Standard Time' = 'America/Chicago'
'Eastern Standard Time' = 'America/New_York'
'US Eastern Standard Time' = 'America/Indiana/Indianapolis'
'Atlantic Standard Time' = 'America/Halifax'
'Newfoundland Standard Time' = 'America/St_Johns'
'Greenland Standard Time' = 'America/Godthab'
'Azores Standard Time' = 'Atlantic/Azores'
'Cape Verde Standard Time' = 'Atlantic/Cape_Verde'
'Argentina Standard Time' = 'America/Argentina/Buenos_Aires'
'SA Pacific Standard Time' = 'America/Bogota'
'SA Western Standard Time' = 'America/La_Paz'
'Pacific SA Standard Time' = 'America/Santiago'
'E. South America Standard Time' = 'America/Sao_Paulo'
}
if ($map.ContainsKey($WindowsTzId)) {
return $map[$WindowsTzId]
}
# Fall back to UTC if unknown — better than passing an invalid ID to .NET.
Write-LogWarn "Could not map Windows timezone '$WindowsTzId' to IANA. Using UTC."
return "UTC"
}
# Restrict NTFS ACLs on a sensitive file so only the current user can read/write it.
# By default, files created under the user profile inherit read access for local
# Users/Authenticated Users, which would leak .env / config.json secrets to any
# other local account. This mirrors `chmod 600` on Linux.
function Lock-FileAcl ($Path) {
if (-not (Test-Path $Path)) { return }
try {
icacls $Path /inheritance:r /grant:r "$($env:USERNAME):(F)" 2>&1 | Out-Null
} catch {
Write-LogWarn "Could not lock ACLs on $Path — file may be readable by other users."
}
}
# Parse a KEY=value .env file into a hashtable. Used to preserve existing
# API keys / credentials across re-runs so integrations don't break.
function Read-EnvFile ($Path) {
$result = @{}
if (-not (Test-Path $Path)) { return $result }
foreach ($line in (Get-Content -Path $Path)) {
$trimmed = $line.Trim()
if ($trimmed -eq "" -or $trimmed.StartsWith("#")) { continue }
$idx = $trimmed.IndexOf("=")
if ($idx -lt 1) { continue }
$name = $trimmed.Substring(0, $idx).Trim()
$value = $trimmed.Substring($idx + 1).Trim().Trim('"').Trim("'")
$result[$name] = $value
}
return $result
}
$SvcOrder = @('decypharr', 'prowlarr', 'byparr', 'radarr', 'sonarr', 'seerr')
$SvcPorts = @{
'decypharr' = 8282; 'prowlarr' = 9696; 'byparr' = 8191;
'radarr' = 7878; 'sonarr' = 8989; 'seerr' = 5055
}
$SvcLabels = @{
'decypharr' = 'Decypharr'; 'prowlarr' = 'Prowlarr'; 'byparr' = 'Byparr';
'radarr' = 'Radarr'; 'sonarr' = 'Sonarr'; 'seerr' = 'Seerr'
}
function Invoke-PrintServiceUrls {
foreach ($svc in $SvcOrder) {
Write-Host " $($SvcLabels[$svc])" -NoNewline
Write-Host " http://localhost:$($SvcPorts[$svc])"
}
if ($global:MediaServer -eq 'plex') {
Write-Host " Plex http://localhost:32400/web"
} else {
Write-Host " Jellyfin http://localhost:8096"
}
}
function Test-Dependencies {
Write-LogSection "System Checks"
$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
Write-LogWarn "Not running as Administrator. Creating the default mount directory (C:\torbox-media) or initializing system mounts may fail without elevated privileges."
}
$missing = @()
if (-not (Get-Command "docker" -ErrorAction SilentlyContinue)) {
$missing += "Docker Desktop"
}
if (-not (Get-Command "curl" -ErrorAction SilentlyContinue)) {
$missing += "curl"
}
if ($missing.Count -gt 0) {
Write-LogError "Missing required dependencies: $($missing -join ', ')"
Write-LogError "Please install Docker Desktop and other tools manually on Windows."
return $false
}
$dockerInfo = docker info 2>&1
if ($LASTEXITCODE -ne 0) {
Write-LogError "Docker daemon is not running or accessible. Please start Docker Desktop."
return $false
}
Write-LogInfo "All dependencies satisfied."
return $true
}
function Test-PortConflicts {
$portsToCheck = @()
foreach ($svc in $SvcOrder) { $portsToCheck += $SvcPorts[$svc] }
if ($global:MediaServer -eq 'plex') { $portsToCheck += 32400 }
elseif ($global:MediaServer -eq 'jellyfin') { $portsToCheck += 8096 }
$conflicts = $false
$netstatOutput = netstat -ano
foreach ($port in $portsToCheck) {
if ($netstatOutput -match ":$port\s+") {
Write-LogWarn "Port $port is already in use."
$conflicts = $true
}
}
if ($conflicts) {
Write-LogWarn "Some ports are in use. Services using those ports may fail to start."
if ($NonInteractive) {
Write-LogWarn "Non-interactive mode: continuing despite port conflicts."
} else {
$ans = Read-Host "Continue anyway? [Y/n]"
if ($ans.ToLower() -eq 'n') {
Write-LogError "Setup cancelled."
return $false
}
}
}
return $true
}
function Invoke-CheckExistingInstallation {
# Populated with values preserved from a prior install; empty otherwise.
$global:ExistingEnv = @{}
if (Test-Path $SetupCompleteFile) {
Write-LogSection "Existing Installation Detected"
Write-LogWarn "A previous installation was found at: $InstallDir"
Write-Host ""
Write-Host " Re-running will regenerate Docker Compose and configs."
Write-Host " Your existing API keys will be PRESERVED to avoid breaking integrations."
Write-Host ""
if (-not $NonInteractive) {
$rerun = Read-Host "Continue with re-configuration? [y/N]"
if ($rerun.ToLower() -ne 'y') {
Write-LogInfo "Setup cancelled. Your existing installation is unchanged."
exit 0
}
}
# Back up existing generated files before overwriting.
$backupTs = Get-Date -Format "yyyyMMdd_HHmmss"
foreach ($bf in @($EnvFile, $ComposeFile, "$ConfigDir\decypharr\config.json")) {
if (Test-Path $bf) { Copy-Item -Path $bf -Destination "$bf.bak.$backupTs" -Force }
}
Write-LogInfo "Backed up existing config files (.bak.$backupTs)."
$global:ExistingEnv = Read-EnvFile $EnvFile
# Drop API keys that aren't valid 32-char hex so they get regenerated.
foreach ($k in @('RADARR_API_KEY', 'SONARR_API_KEY', 'PROWLARR_API_KEY')) {
if ($global:ExistingEnv.ContainsKey($k) -and $global:ExistingEnv[$k] -notmatch '^[0-9a-f]{32}$') {
Write-LogWarn "Corrupted API key detected for $k. Will regenerate."
$global:ExistingEnv.Remove($k)
}
}
if ($global:ExistingEnv.ContainsKey('RADARR_API_KEY')) {
Write-LogInfo "Existing API keys loaded and will be preserved."
}
Write-Host ""
} elseif ((Test-Path $EnvFile) -and -not (Test-Path $SetupCompleteFile)) {
# .env exists but setup never completed — a prior run was interrupted.
Write-LogSection "Incomplete Installation Detected"
Write-LogWarn "A previous setup was interrupted before completion."
Write-LogWarn "Starting fresh (incomplete state will be cleaned up)."
Write-Host ""
Remove-Item -Path $InstallDir -Recurse -Force -ErrorAction SilentlyContinue
}
}
# Reuse a preserved value from a prior install, or fall back to a generator.
function Get-OrNew ($EnvKey, [scriptblock]$Generator) {
if ($global:ExistingEnv -and $global:ExistingEnv.ContainsKey($EnvKey) -and -not [string]::IsNullOrEmpty($global:ExistingEnv[$EnvKey])) {
return $global:ExistingEnv[$EnvKey]
}
return (& $Generator)
}
function Invoke-GatherConfig {
Write-LogSection "Configuration"
Write-Host "TorBox API Key" -ForegroundColor White
Write-Host " Get your API key from: https://torbox.app/settings"
$TorboxApiKey = $env:TORBOX_API_KEY
$existingTorboxKey = ""
if ($global:ExistingEnv -and $global:ExistingEnv.ContainsKey('TORBOX_API_KEY')) {
$existingTorboxKey = $global:ExistingEnv['TORBOX_API_KEY']
}
if ([string]::IsNullOrEmpty($TorboxApiKey)) {
if (-not [string]::IsNullOrEmpty($existingTorboxKey)) {
# Re-run: keep the saved key unless the user enters a new one.
if ($NonInteractive) {
$TorboxApiKey = $existingTorboxKey
Write-LogInfo "Reusing existing TorBox API key."
} else {
Write-Host " An existing TorBox API key was found ($(Get-MaskedKey $existingTorboxKey))."
$secureStr = Read-Host -AsSecureString " Enter a new TorBox API key (or press Enter to keep existing)"
$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureStr)
$TorboxApiKey = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)
if ([string]::IsNullOrEmpty($TorboxApiKey)) { $TorboxApiKey = $existingTorboxKey }
}
} elseif ($NonInteractive) {
Write-LogError "Non-interactive mode requires TORBOX_API_KEY environment variable."
return $false
} else {
while ([string]::IsNullOrEmpty($TorboxApiKey)) {
$secureStr = Read-Host -AsSecureString " Enter your TorBox API key"
$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureStr)
$TorboxApiKey = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)
if ([string]::IsNullOrEmpty($TorboxApiKey)) { Write-LogError "API key cannot be empty." }
}
}
}
if ($TorboxApiKey -notmatch "^[a-zA-Z0-9._-]+$") {
Write-LogError "API key contains invalid characters."
return $false
}
Write-LogInfo "API key received ($($TorboxApiKey.Length) characters)."
$global:TorboxApiKey = $TorboxApiKey
Write-Host "`nMedia Server" -ForegroundColor White
$MediaServer = $env:TORBOX_MEDIA_SERVER
if ([string]::IsNullOrEmpty($MediaServer)) {
if ($NonInteractive) {
$MediaServer = "plex"
Write-LogInfo "Non-interactive mode: defaulting to Plex."
} else {
Write-Host " 1) Plex"
Write-Host " 2) Jellyfin"
while ($true) {
$choice = Read-Host " Choose your media server [1/2]"
if ($choice -eq '1') { $MediaServer = "plex"; break }
if ($choice -eq '2') { $MediaServer = "jellyfin"; break }
Write-LogError "Please enter 1 or 2."
}
}
}
if ($MediaServer -notin @("plex", "jellyfin")) { $MediaServer = "plex" }
$global:MediaServer = $MediaServer
$PlexClaim = $env:TORBOX_PLEX_CLAIM
if ($MediaServer -eq "plex" -and [string]::IsNullOrEmpty($PlexClaim) -and -not $NonInteractive) {
Write-Host "`nPlex Claim Token (optional, for first-time setup)" -ForegroundColor White
$PlexClaim = Read-Host " Plex claim token"
}
$global:PlexClaim = $PlexClaim
$global:MountDir = $env:TORBOX_MOUNT_DIR
if ([string]::IsNullOrEmpty($global:MountDir)) { $global:MountDir = "C:\torbox-media" }
if (-not $NonInteractive) {
$customMount = Read-Host "`nMount Directory [$global:MountDir] (Press Enter to accept)"
if (-not [string]::IsNullOrEmpty($customMount)) { $global:MountDir = $customMount }
}
$global:PUID = 1000
$global:PGID = 1000
# Convert the Windows timezone ID to an IANA name — Linux containers (and
# .NET-on-Linux apps like Radarr/Sonarr) only understand IANA names. Without
# this, the *arr apps would silently fall back to UTC.
$global:TZ = ConvertTo-IanaTimezone ([System.TimeZoneInfo]::Local.Id)
# Preserve existing keys/credentials across re-runs; only generate when absent.
$global:RadarrApiKey = Get-OrNew 'RADARR_API_KEY' { New-ApiKey }
$global:SonarrApiKey = Get-OrNew 'SONARR_API_KEY' { New-ApiKey }
$global:ProwlarrApiKey = Get-OrNew 'PROWLARR_API_KEY' { New-ApiKey }
$global:RadarrAdminUser = Get-OrNew 'RADARR_ADMIN_USER' { "admin" }
$global:RadarrAdminPass = Get-OrNew 'RADARR_ADMIN_PASS' { New-AdminPass }
$global:SonarrAdminUser = Get-OrNew 'SONARR_ADMIN_USER' { "admin" }
$global:SonarrAdminPass = Get-OrNew 'SONARR_ADMIN_PASS' { New-AdminPass }
$global:ProwlarrAdminUser = Get-OrNew 'PROWLARR_ADMIN_USER' { "admin" }
$global:ProwlarrAdminPass = Get-OrNew 'PROWLARR_ADMIN_PASS' { New-AdminPass }
$global:DecypharrUser = Get-OrNew 'DECYPHARR_USER' { "torbox" }
$global:DecypharrPass = Get-OrNew 'DECYPHARR_PASS' { New-AdminPass }
return $true
}
function Invoke-CreateDirectories {
Write-LogSection "Preparing Directories"
$dirs = @(
$InstallDir,
"$ConfigDir\prowlarr",
"$ConfigDir\radarr",
"$ConfigDir\sonarr",
"$ConfigDir\seerr",
"$ConfigDir\decypharr",
"$ConfigDir\$global:MediaServer",
"$DataDir\media\movies",
"$DataDir\media\tv",
"$DataDir\downloads\radarr",
"$DataDir\downloads\sonarr"
)
foreach ($dir in $dirs) {
if (-not (Test-Path $dir)) {
New-Item -ItemType Directory -Force -Path $dir | Out-Null
}
}
if (-not (Test-Path $global:MountDir)) {
New-Item -ItemType Directory -Force -Path $global:MountDir | Out-Null
}
}
function Invoke-GenerateDecypharrConfig {
Write-LogStep "Generating Decypharr config..."
# Validate user-supplied credentials before interpolating into JSON — env
# vars could otherwise break the JSON document (double quotes, backslashes).
if (-not ($global:DecypharrUser -match '^[a-zA-Z0-9_-]{1,32}$')) {
Write-LogWarn "DECYPHARR_USER contains characters unsafe for JSON. Using default 'torbox'."
$global:DecypharrUser = "torbox"
}
if (-not [string]::IsNullOrEmpty($global:DecypharrPass) -and
-not ($global:DecypharrPass -match '^[a-zA-Z0-9_./+=-]+$')) {
Write-LogWarn "DECYPHARR_PASS contains characters unsafe for JSON. Regenerating."
$global:DecypharrPass = New-AdminPass
}
# If a config already exists, refresh the TorBox API key instead of
# skipping — otherwise rotating TORBOX_API_KEY would silently leave
# Decypharr using the old key, desynchronizing it from .env.
$decypharrConfigPath = "$ConfigDir\decypharr\config.json"
if (Test-Path $decypharrConfigPath) {
try {
$cfg = Get-Content $decypharrConfigPath -Raw | ConvertFrom-Json
if ($cfg.debrids -and $cfg.debrids.Count -gt 0) {
$cfg.debrids[0].api_key = $global:TorboxApiKey
}
$cfg.username = $global:DecypharrUser
if (-not [string]::IsNullOrEmpty($global:DecypharrPass)) {
$cfg.password = $global:DecypharrPass
}
Write-TextFile -Path $decypharrConfigPath -Content ($cfg | ConvertTo-Json -Depth 10)
Lock-FileAcl $decypharrConfigPath
Write-LogInfo "Refreshed TorBox API key in existing Decypharr config."
return
} catch {
Write-LogWarn "Could not update existing Decypharr config via JSON parse: $($_.Exception.Message)"
Write-LogWarn "Old API key may be retained. Edit $decypharrConfigPath manually if needed."
return
}
}
# Generate a fresh config matching setup.sh's schema (debrids[] array,
# rclone mount, qbittorrent categories, top-level username/password).
# This must match setup.sh so both platforms produce a working Decypharr v2.0
# config — diverging schemas caused broken qBittorrent mocks on one platform.
$configJson = @"
{
"debrids": [
{
"name": "torbox",
"api_key": "$($global:TorboxApiKey)",
"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": "$($global:DecypharrUser)",
"password": "$($global:DecypharrPass)",
"port": "8282",
"log_level": "info"
}
"@
Write-TextFile -Path $decypharrConfigPath -Content $configJson
Lock-FileAcl $decypharrConfigPath
}
function Invoke-GenerateArrConfigs {
Write-LogStep "Generating configs for *arr apps..."
$arrs = @(
@{ name = "radarr"; key = $global:RadarrApiKey },
@{ name = "sonarr"; key = $global:SonarrApiKey },
@{ name = "prowlarr"; key = $global:ProwlarrApiKey }
)
foreach ($arr in $arrs) {
$name = $arr.name
$key = $arr.key
$configXml = @"
<Config>
<LogLevel>info</LogLevel>
<UpdateMechanism>Docker</UpdateMechanism>
<AuthenticationMethod>Forms</AuthenticationMethod>
<AuthenticationRequired>Enabled</AuthenticationRequired>
<AnalyticsEnabled>False</AnalyticsEnabled>
<ApiKey>$key</ApiKey>
</Config>
"@
Write-TextFile -Path "$ConfigDir\$name\config.xml" -Content $configXml
Lock-FileAcl "$ConfigDir\$name\config.xml"
}
}
function Invoke-GenerateDockerCompose {
Write-LogStep "Setting up Docker Compose..."
$SourceFile = Join-Path $ScriptDir "docker-compose.yml"
if (-not (Test-Path $SourceFile)) {
Write-LogWarn "Source docker-compose.yml not found at: $SourceFile"
Write-LogStep "Failed to set up Docker Compose."
return
}
Copy-Item -Path $SourceFile -Destination $ComposeFile -Force
Write-LogInfo "Copied docker-compose.yml to: $ComposeFile"
$OverrideFile = Join-Path $InstallDir "docker-compose.override.yml"
if (Test-Path $OverrideFile) { Remove-Item -Path $OverrideFile -Force }
try {
Set-Location $InstallDir
docker compose config -q 2>&1 | Out-Null
if ($LASTEXITCODE -eq 0) {
Write-LogInfo "Docker Compose file at $ComposeFile validated successfully."
} else {
Write-LogWarn "Docker Compose validation failed for $ComposeFile."
}
} catch {
Write-LogWarn "Docker daemon not accessible or compose failed."
}
}
function Invoke-GenerateEnvFile {
Write-LogStep "Generating .env file..."
# Escape backslashes in MOUNT_DIR so consumers that interpret backslash
# escapes (e.g. YAML, JSON, .env loaders) don't turn \t into a tab or \n
# into a newline. Forward slashes work fine on Windows for Docker Compose
# volume mounts, so we normalize to those.
$mountDirEscaped = $global:MountDir -replace '\\', '/'
$envContent = @"
# ============================================================================
# TorBox Media Server - Environment Configuration
# ============================================================================
# User / System
PUID=$($global:PUID)
PGID=$($global:PGID)
TZ=$($global:TZ)
# Directories
INSTALL_DIR=$InstallDir
CONFIG_DIR=$ConfigDir
DATA_DIR=$DataDir
MOUNT_DIR=$mountDirEscaped
# Core Credentials
TORBOX_API_KEY=$global:TorboxApiKey
MEDIA_SERVER=$global:MediaServer
# Decypharr
DECYPHARR_USER=$global:DecypharrUser
DECYPHARR_PASS=$global:DecypharrPass
# Radarr
RADARR_API_KEY=$global:RadarrApiKey
RADARR_ADMIN_USER=$global:RadarrAdminUser
RADARR_ADMIN_PASS=$global:RadarrAdminPass
# Sonarr
SONARR_API_KEY=$global:SonarrApiKey
SONARR_ADMIN_USER=$global:SonarrAdminUser
SONARR_ADMIN_PASS=$global:SonarrAdminPass
# Prowlarr
PROWLARR_API_KEY=$global:ProwlarrApiKey
PROWLARR_ADMIN_USER=$global:ProwlarrAdminUser
PROWLARR_ADMIN_PASS=$global:ProwlarrAdminPass
COMPOSE_PROFILES=$global:MediaServer
"@
if (-not [string]::IsNullOrEmpty($global:PlexClaim)) {
$envContent += "`nPLEX_CLAIM=$global:PlexClaim"
}
Write-TextFile -Path $EnvFile -Content ($envContent + "`n")
# Restrict ACLs to the current user only — .env contains TORBOX_API_KEY,
# *_ADMIN_PASS, and DECYPHARR_PASS. Without this, any local user could read it.
Lock-FileAcl $EnvFile
}
function Invoke-StartServices {
Write-LogSection "Starting Services"
$startNow = 'y'
if (-not $NonInteractive) {
$startNow = Read-Host "Start all services now? [Y/n]"
}
if ($startNow.ToLower() -ne 'n') {
Write-LogStep "Starting Docker containers..."
Set-Location $InstallDir
docker compose --env-file .env up -d --remove-orphans
if ($LASTEXITCODE -ne 0) {
Write-LogError "Failed to start services."
return
}
Write-LogInfo "All services starting! Give them 30-60 seconds to initialize."
$global:ServicesStarted = $true
} else {
Write-LogInfo "You can start services later manually via docker compose."
$global:ServicesStarted = $false
}
}
function Wait-ForService {
param (
[string]$Name,
[string]$Url,
[string]$ApiKey,
[int]$MaxWait = 90,
[string]$ApiVer = "v3"
)
$elapsed = 0
$interval = 3
while ($elapsed -lt $MaxWait) {
try {
$headers = @{}
if ($ApiKey) { $headers["X-Api-Key"] = $ApiKey }
$res = Invoke-RestMethod -Uri "$Url/api/$ApiVer/system/status" -Method Get -Headers $headers -ErrorAction Stop
Write-LogInfo "$Name is ready. ($($elapsed)s)"
return $true
} catch {
Write-Host -NoNewline "`r Waiting for $Name... $($elapsed)s/$($MaxWait)s"
Start-Sleep -Seconds $interval
$elapsed += $interval
}
}
Write-LogWarn "$Name did not become ready within $MaxWait seconds."
return $false
}
function Invoke-ConfigureArrAuth {
param (
[string]$Name,
[string]$Url,
[string]$ApiKey,
[string]$ApiVer = "v3"
)
try {
$headers = @{ "X-Api-Key" = $ApiKey; "Content-Type" = "application/json" }
$settingsUrl = if ($ApiVer -eq "v1") { "$Url/api/v1/config/host" } else { "$Url/api/v3/config/host" }
$config = Invoke-RestMethod -Uri $settingsUrl -Method Get -Headers $headers -ErrorAction Stop
$userVar = "$($Name)AdminUser"
$passVar = "$($Name)AdminPass"
$user = (Get-Variable -Name $userVar -Scope Global -ValueOnly -ErrorAction SilentlyContinue)
$pass = (Get-Variable -Name $passVar -Scope Global -ValueOnly -ErrorAction SilentlyContinue)
if ($user -and $pass) {
$config.authenticationMethod = "forms"
$config.authenticationRequired = "enabled"
$config.username = $user
$config.password = $pass
Invoke-RestMethod -Uri $settingsUrl -Method Put -Headers $headers -Body ($config | ConvertTo-Json -Depth 10) -ErrorAction Stop | Out-Null
Write-LogInfo " $Name authentication configured (Forms)."
}
} catch {
Write-LogWarn " Failed to configure authentication for $Name."
}
}
function Invoke-AddDefaultIndexer {
try {
$headers = @{ "X-Api-Key" = $global:ProwlarrApiKey; "Content-Type" = "application/json" }
$url = "http://localhost:$($SvcPorts['prowlarr'])/api/v1/indexer"
$indexers = Invoke-RestMethod -Uri $url -Method Get -Headers $headers -ErrorAction Stop
$exists = $false
foreach ($i in $indexers) {
if ($i.name -eq "1337x") { $exists = $true; break }
}
if (-not $exists) {
$body = @{
enable = $true
name = "1337x"
implementation = "Cardigann"
configContract = "CardigannSettings"
protocol = "torrent"
appProfileId = 1
fields = @(
@{ name = "baseUrl"; value = "https://1337x.to/" },
@{ name = "indexerProxyAccessType"; value = "proxy" }
)
}
Invoke-RestMethod -Uri $url -Method Post -Headers $headers -Body ($body | ConvertTo-Json -Depth 10) -ErrorAction Stop | Out-Null
Write-LogInfo " Added default indexer (1337x) to Prowlarr."
}
} catch {
Write-LogWarn " Failed to add default indexer to Prowlarr."
}
}
function Invoke-ConfigureSeerr {
Write-LogStep "Auto-configuring Seerr..."
$seerrUrl = "http://localhost:$($SvcPorts['seerr'])"
$elapsed = 0; $maxWait = 60; $interval = 3
$ready = $false
while ($elapsed -lt $maxWait) {
try {
Invoke-RestMethod -Uri "$seerrUrl/api/v1/status" -Method Get -ErrorAction Stop | Out-Null
Write-LogInfo "Seerr is ready. ($($elapsed)s)"
$ready = $true
break
} catch {
Start-Sleep -Seconds $interval
$elapsed += $interval
}
}
if (-not $ready) {
Write-LogWarn "Seerr did not become ready."
return $false
}
try {
$radarrProfiles = Invoke-RestMethod -Uri "http://localhost:$($SvcPorts['radarr'])/api/v3/qualityprofile" -Headers @{"X-Api-Key"=$global:RadarrApiKey}
$radarrProfileId = if ($radarrProfiles.Count -gt 0) { $radarrProfiles[0].id } else { 1 }
$sonarrProfiles = Invoke-RestMethod -Uri "http://localhost:$($SvcPorts['sonarr'])/api/v3/qualityprofile" -Headers @{"X-Api-Key"=$global:SonarrApiKey}
$sonarrProfileId = if ($sonarrProfiles.Count -gt 0) { $sonarrProfiles[0].id } else { 1 }
$radarrBody = @{
name = "Radarr"
hostname = "radarr"
port = 7878
apiKey = $global:RadarrApiKey
useSsl = $false
baseUrl = ""
activeProfileId = $radarrProfileId
activeProfileName = ""
activeDirectory = "/data/media/movies"
is4k = $false
isDefault = $true
syncEnabled = $true
preventSearch = $false
}
Invoke-RestMethod -Uri "$seerrUrl/api/v1/settings/radarr" -Method Post -Body ($radarrBody | ConvertTo-Json -Depth 10) -ContentType "application/json" -ErrorAction Stop | Out-Null
Write-LogInfo " Radarr added to Seerr."
$sonarrBody = @{
name = "Sonarr"
hostname = "sonarr"
port = 8989
apiKey = $global:SonarrApiKey
useSsl = $false
baseUrl = ""
activeProfileId = $sonarrProfileId
activeProfileName = ""
activeDirectory = "/data/media/tv"
activeLanguageProfileId = 1
activeAnimeProfileId = $sonarrProfileId
activeAnimeLanguageProfileId = 1
activeAnimeDirectory = "/data/media/tv"
is4k = $false
isDefault = $true
syncEnabled = $true
preventSearch = $false
}
Invoke-RestMethod -Uri "$seerrUrl/api/v1/settings/sonarr" -Method Post -Body ($sonarrBody | ConvertTo-Json -Depth 10) -ContentType "application/json" -ErrorAction Stop | Out-Null
Write-LogInfo " Sonarr added to Seerr."
return $true
} catch {
Write-LogWarn " Failed to configure Seerr integrations."
return $false
}
}
function Invoke-ConfigurePlexLibraries {
if ($global:MediaServer -ne "plex") { return $true }
$plexUrl = "http://localhost:32400"
$elapsed = 0; $maxWait = 60; $interval = 3
$ready = $false
while ($elapsed -lt $maxWait) {
try {
$status = Invoke-RestMethod -Uri "$plexUrl/identity" -Method Get -ErrorAction Stop
if ($status) { $ready = $true; break }
} catch {
Start-Sleep -Seconds $interval
$elapsed += $interval
}
}
if (-not $ready) {
Write-LogWarn "Plex did not become ready."
return $false
}
try {
$prefs = Invoke-RestMethod -Uri "$plexUrl/web/index.html" -Method Get -ErrorAction SilentlyContinue
# Getting the token directly from local Plex is difficult without user login,
# so this might not work perfectly. We'll skip complex library setup for Plex as it usually requires
# a valid X-Plex-Token obtained after user claim/login which can be tricky to automate locally on windows without sed-ing Preferences.xml easily.
# But we can try to find Preferences.xml
$plexConfigDir = "$ConfigDir\plex\Library\Application Support\Plex Media Server"
$prefsFile = "$plexConfigDir\Preferences.xml"
$token = ""
if (Test-Path $prefsFile) {
$content = Get-Content $prefsFile -Raw
if ($content -match 'PlexOnlineToken="([^"]+)"') {
$token = $matches[1]
}
}
if ($token) {
# Check libraries
$libs = Invoke-RestMethod -Uri "$plexUrl/library/sections" -Headers @{"X-Plex-Token"=$token} -ErrorAction SilentlyContinue
# Creating libraries via API is complex, we will log it.
Write-LogInfo "Plex Token found. Library creation via API is complex, please create them manually."
} else {
Write-LogWarn "Plex token not found. Please create libraries manually."
}
return $true
} catch {
Write-LogWarn "Failed to configure Plex libraries."
return $false
}
}
function Invoke-ConfigureArrService {
param (
[string]$Name,
[string]$Url,
[string]$ApiKey,
[string]$Type,
[int]$Port,
[string]$RootPath,
[hashtable]$NamingUpdates
)
try {
$headers = @{ "X-Api-Key" = $ApiKey; "Content-Type" = "application/json" }
# Add Download Client (Decypharr as qBittorrent)
$clients = Invoke-RestMethod -Uri "$Url/api/v3/downloadclient" -Headers $headers -ErrorAction Stop
$clientExists = $false
foreach ($c in $clients) {
if ($c.name -eq "Decypharr") { $clientExists = $true; break }
}
if (-not $clientExists) {
# Decypharr presents itself as a qBittorrent mock. It identifies the
# calling *arr via username=internal URL + password=API key, and routes
# by category. These fields must match setup.sh for the integration to work.
$internalUrl = "http://$($Type):$($Port)"
if ($Type -eq "sonarr") {
$catField = "tvCategory"; $catImportedField = "tvImportedCategory"
} else {
$catField = "movieCategory"; $catImportedField = "movieImportedCategory"
}
$body = @{
enable = $true
name = "Decypharr"
implementation = "QBittorrent"
configContract = "QBittorrentSettings"
protocol = "torrent"
priority = 1
removeCompletedDownloads = $true
removeFailedDownloads = $true
fields = @(
@{ name = "host"; value = "decypharr" },
@{ name = "port"; value = 8282 },
@{ name = "useSsl"; value = $false },
@{ name = "username"; value = $internalUrl },
@{ name = "password"; value = $ApiKey },
@{ name = $catField; value = $Type },
@{ name = $catImportedField; value = "" },
@{ name = "initialState"; value = 0 },
@{ name = "sequentialOrder"; value = $false },
@{ name = "firstAndLastFirst"; value = $false }
)
}
Invoke-RestMethod -Uri "$Url/api/v3/downloadclient?forceSave=true" -Method Post -Headers $headers -Body ($body | ConvertTo-Json -Depth 10) -ErrorAction Stop | Out-Null
Write-LogInfo " Decypharr download client added to $Name."
}
# Add Root Folder
$folders = Invoke-RestMethod -Uri "$Url/api/v3/rootfolder" -Headers $headers -ErrorAction Stop
$folderExists = $false
foreach ($f in $folders) {
if ($f.path -eq $RootPath) { $folderExists = $true; break }
}
if (-not $folderExists) {
$body = @{ path = $RootPath }
Invoke-RestMethod -Uri "$Url/api/v3/rootfolder" -Method Post -Headers $headers -Body ($body | ConvertTo-Json -Depth 10) -ErrorAction Stop | Out-Null
Write-LogInfo " Root folder $RootPath added to $Name."
}
# Update Media Management (Hardlinks disabled)
$mm = Invoke-RestMethod -Uri "$Url/api/v3/config/mediamanagement" -Headers $headers -ErrorAction Stop
$mm.copyUsingHardlinks = $false
Invoke-RestMethod -Uri "$Url/api/v3/config/mediamanagement" -Method Put -Headers $headers -Body ($mm | ConvertTo-Json -Depth 10) -ErrorAction Stop | Out-Null
# Update Naming
$naming = Invoke-RestMethod -Uri "$Url/api/v3/config/naming" -Headers $headers -ErrorAction Stop
foreach ($key in $NamingUpdates.Keys) {
$naming.$key = $NamingUpdates[$key]
}
Invoke-RestMethod -Uri "$Url/api/v3/config/naming" -Method Put -Headers $headers -Body ($naming | ConvertTo-Json -Depth 10) -ErrorAction Stop | Out-Null
Write-LogInfo " Media management and naming configured for $Name."
} catch {
Write-LogWarn " Failed to configure $Name."
}
}
function Invoke-ConfigureArrs {
Write-LogSection "Configuring Services via API"
$radarrUrl = "http://localhost:$($SvcPorts['radarr'])"
$sonarrUrl = "http://localhost:$($SvcPorts['sonarr'])"
$prowlarrUrl = "http://localhost:$($SvcPorts['prowlarr'])"
$radarrReady = Wait-ForService -Name "Radarr" -Url $radarrUrl -ApiKey $global:RadarrApiKey -MaxWait 90 -ApiVer "v3"
$sonarrReady = Wait-ForService -Name "Sonarr" -Url $sonarrUrl -ApiKey $global:SonarrApiKey -MaxWait 90 -ApiVer "v3"
$prowlarrReady = Wait-ForService -Name "Prowlarr" -Url $prowlarrUrl -ApiKey $global:ProwlarrApiKey -MaxWait 90 -ApiVer "v1"
Start-Sleep -Seconds 3
if ($radarrReady) {
$radarrNaming = @{
renameMovies = $true
replaceIllegalCharacters = $true
colonReplacementFormat = "dash"
standardMovieFormat = "{Movie CleanTitle} ({Release Year}) [{Quality Full}]"
movieFolderFormat = "{Movie CleanTitle} ({Release Year}) [imdbid-{ImdbId}]"
}
Invoke-ConfigureArrService -Name "Radarr" -Url $radarrUrl -ApiKey $global:RadarrApiKey -Type "radarr" -Port 7878 -RootPath "/data/media/movies" -NamingUpdates $radarrNaming
}
if ($sonarrReady) {
$sonarrNaming = @{
renameEpisodes = $true
replaceIllegalCharacters = $true
colonReplacementFormat = 4
standardEpisodeFormat = "{Series TitleYear} - S{season:00}E{episode:00} - {Episode CleanTitle} [{Quality Full}]"
dailyEpisodeFormat = "{Series TitleYear} - {Air-Date} - {Episode CleanTitle} [{Quality Full}]"
animeEpisodeFormat = "{Series TitleYear} - S{season:00}E{episode:00} - {Episode CleanTitle} [{Quality Full}]"