# Jellyfin Windows Path Fixer
# This script checks and fixes Linux paths in Jellyfin configuration files

param(
    [string]$ConfigPath = "C:\ProgramData\jellyfin\config",
    [string]$DataPath = "C:\ProgramData\jellyfin\data",
    [switch]$DryRun = $false,
    [switch]$Force = $false
)

Write-Host "=================================================" -ForegroundColor Cyan
Write-Host "Jellyfin Windows Path Fixer" -ForegroundColor Cyan
Write-Host "=================================================" -ForegroundColor Cyan
Write-Host ""

# Check if config path exists
if (-not (Test-Path $ConfigPath)) {
    Write-Host "ERROR: Config path not found: $ConfigPath" -ForegroundColor Red
    Write-Host "Please specify the correct path using -ConfigPath parameter" -ForegroundColor Yellow
    exit 1
}

Write-Host "Config Path: $ConfigPath" -ForegroundColor Green
Write-Host "Data Path: $DataPath" -ForegroundColor Green
Write-Host ""

$issuesFound = @()

# Function to check XML file for Linux paths
function Test-LinuxPathsInXml {
    param(
        [string]$FilePath,
        [string]$FileName
    )
    
    if (-not (Test-Path $FilePath)) {
        Write-Host "  [SKIP] $FileName - File not found" -ForegroundColor Gray
        return $null
    }
    
    try {
        [xml]$xml = Get-Content $FilePath
        $linuxPaths = @()
        
        # Check all text nodes for Linux paths
        $xml.SelectNodes("//*") | ForEach-Object {
            if ($_.InnerText -match '^(/var/|/usr/|/etc/)') {
                $linuxPaths += @{
                    Element = $_.Name
                    CurrentValue = $_.InnerText
                    Line = $_.OuterXml
                }
            }
        }
        
        if ($linuxPaths.Count -gt 0) {
            Write-Host "  [ISSUE] $FileName - Found $($linuxPaths.Count) Linux path(s)" -ForegroundColor Yellow
            return @{
                FilePath = $FilePath
                FileName = $FileName
                LinuxPaths = $linuxPaths
            }
        } else {
            Write-Host "  [OK] $FileName - No Linux paths found" -ForegroundColor Green
            return $null
        }
    }
    catch {
        Write-Host "  [ERROR] $FileName - Failed to parse: $_" -ForegroundColor Red
        return $null
    }
}

# Check configuration files
Write-Host "Checking configuration files..." -ForegroundColor Cyan
Write-Host ""

$systemXmlPath = Join-Path $ConfigPath "system.xml"
$result = Test-LinuxPathsInXml -FilePath $systemXmlPath -FileName "system.xml"
if ($result) {
    $issuesFound += $result
    foreach ($path in $result.LinuxPaths) {
        Write-Host "    - $($path.Element): $($path.CurrentValue)" -ForegroundColor Red
    }
}

$encodingXmlPath = Join-Path $ConfigPath "encoding.xml"
$result = Test-LinuxPathsInXml -FilePath $encodingXmlPath -FileName "encoding.xml"
if ($result) {
    $issuesFound += $result
    foreach ($path in $result.LinuxPaths) {
        Write-Host "    - $($path.Element): $($path.CurrentValue)" -ForegroundColor Red
    }
}

$databaseXmlPath = Join-Path $ConfigPath "database.xml"
$result = Test-LinuxPathsInXml -FilePath $databaseXmlPath -FileName "database.xml"
if ($result) {
    $issuesFound += $result
    foreach ($path in $result.LinuxPaths) {
        Write-Host "    - $($path.Element): $($path.CurrentValue)" -ForegroundColor Red
    }
}

Write-Host ""
Write-Host "=================================================" -ForegroundColor Cyan

# Summary
if ($issuesFound.Count -eq 0) {
    Write-Host "No issues found! All paths are correct." -ForegroundColor Green
    exit 0
}

Write-Host "Found issues in $($issuesFound.Count) file(s)" -ForegroundColor Yellow
Write-Host ""

# If DryRun, just show what would be done
if ($DryRun) {
    Write-Host "DRY RUN MODE - No changes will be made" -ForegroundColor Cyan
    Write-Host ""
    Write-Host "The following changes would be made:" -ForegroundColor Yellow
    
    foreach ($issue in $issuesFound) {
        Write-Host ""
        Write-Host "File: $($issue.FileName)" -ForegroundColor Cyan
        foreach ($path in $issue.LinuxPaths) {
            Write-Host "  $($path.Element):" -ForegroundColor White
            Write-Host "    FROM: $($path.CurrentValue)" -ForegroundColor Red
            
            if ($path.Element -in @("MetadataPath", "TranscodingTempPath")) {
                Write-Host "    TO:   (empty - use default)" -ForegroundColor Green
            } else {
                $newPath = $path.CurrentValue -replace '^/var/lib/jellyfin', $DataPath -replace '/', '\'
                Write-Host "    TO:   $newPath" -ForegroundColor Green
            }
        }
    }
    
    Write-Host ""
    Write-Host "To apply these changes, run the script without -DryRun" -ForegroundColor Yellow
    exit 0
}

# Ask for confirmation
if (-not $Force) {
    Write-Host ""
    Write-Host "WARNING: This will modify your configuration files!" -ForegroundColor Yellow
    Write-Host "Backups will be created automatically." -ForegroundColor Yellow
    Write-Host ""
    $confirm = Read-Host "Do you want to proceed? (yes/no)"
    if ($confirm -ne "yes") {
        Write-Host "Operation cancelled." -ForegroundColor Red
        exit 0
    }
}

# Apply fixes
Write-Host ""
Write-Host "Applying fixes..." -ForegroundColor Cyan
Write-Host ""

foreach ($issue in $issuesFound) {
    Write-Host "Fixing $($issue.FileName)..." -ForegroundColor Yellow
    
    $timestamp = Get-Date -Format 'yyyyMMdd_HHmmss'
    $backupPath = "$($issue.FilePath).backup.$timestamp"
    Copy-Item $issue.FilePath $backupPath
    Write-Host "  Backup created: $backupPath" -ForegroundColor Gray
    
    [xml]$xml = Get-Content $issue.FilePath
    
    foreach ($path in $issue.LinuxPaths) {
        $element = $null
        $xml.SelectNodes("//*") | ForEach-Object {
            if ($_.InnerText -eq $path.CurrentValue) {
                $element = $_
            }
        }
        
        if ($element) {
            if ($path.Element -in @("MetadataPath", "TranscodingTempPath")) {
                $element.InnerText = ""
                Write-Host "  Cleared $($path.Element)" -ForegroundColor Green
            } else {
                $newPath = $path.CurrentValue -replace '^/var/lib/jellyfin', $DataPath -replace '/', '\'
                $element.InnerText = $newPath
                Write-Host "  Updated $($path.Element) to: $newPath" -ForegroundColor Green
            }
        }
    }
    
    $xml.Save($issue.FilePath)
    Write-Host "  Saved $($issue.FileName)" -ForegroundColor Green
    Write-Host ""
}

Write-Host "=================================================" -ForegroundColor Cyan
Write-Host "All fixes applied successfully!" -ForegroundColor Green
Write-Host ""
Write-Host "NEXT STEPS:" -ForegroundColor Yellow
Write-Host "1. Restart Jellyfin service/application" -ForegroundColor White
Write-Host "2. Check logs to verify paths are now correct" -ForegroundColor White
$configInfo = "3. If issues persist, review backups in: $ConfigPath"
Write-Host $configInfo -ForegroundColor White
Write-Host ""
