<#
.SYNOPSIS
    Deployt GPLX MediaWiki auf den Bitpalast-Server.

.PARAMETER Mode
    skin      - Cavendish-Skin synchronisieren (Standard, schnell)
    templates - Wiki-Seiten-Vorlagen synchronisieren
    all       - Skin + Templates
    initial   - Erstinstallation: gesamten MediaWiki-Core übertragen

.EXAMPLE
    .\deploy.ps1              # Skin deployen
    .\deploy.ps1 -Mode all    # Skin + Templates
    .\deploy.ps1 -Mode initial
#>
param(
    [ValidateSet('skin', 'templates', 'all', 'initial')]
    [string]$Mode = 'skin'
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

# === Config laden ===
$envFile = Join-Path $PSScriptRoot '..' '.deploy.env'
if (-not (Test-Path $envFile)) {
    Write-Error @"
.deploy.env nicht gefunden.
Kopiere .deploy.example.env zu .deploy.env und trage deine Zugangsdaten ein.
"@
    exit 1
}

Get-Content $envFile | ForEach-Object {
    if ($_ -match '^\s*([^#][^=]+)=(.*)$') {
        [System.Environment]::SetEnvironmentVariable($Matches[1].Trim(), $Matches[2].Trim(), 'Process')
    }
}

$deployHost    = $env:DEPLOY_HOST
$deployUser    = $env:DEPLOY_USER
$mwPath        = $env:DEPLOY_MW_PATH
$projectPath   = $env:DEPLOY_PROJECT_PATH
$target        = "${deployUser}@${deployHost}"

foreach ($var in @('DEPLOY_HOST','DEPLOY_USER','DEPLOY_MW_PATH')) {
    if (-not [System.Environment]::GetEnvironmentVariable($var, 'Process')) {
        Write-Error "$var ist nicht in .deploy.env gesetzt."
        exit 1
    }
}

# === WSL rsync oder scp ===
$hasWsl = $null -ne (Get-Command 'wsl' -ErrorAction SilentlyContinue)

function ConvertTo-WslPath([string]$winPath) {
    $abs = [System.IO.Path]::GetFullPath($winPath)
    $drive = $abs.Substring(0, 1).ToLower()
    $rest  = $abs.Substring(2).Replace('\', '/')
    return "/mnt/$drive$rest"
}

function Sync-Dir([string]$localDir, [string]$remoteDir, [bool]$delete = $false) {
    Write-Host "  $localDir" -ForegroundColor DarkGray
    Write-Host "  -> ${target}:${remoteDir}" -ForegroundColor DarkGray

    if ($hasWsl) {
        $wslSrc  = (ConvertTo-WslPath $localDir) + '/'
        $rsyncArgs = @('-az', '--progress')
        if ($delete) { $rsyncArgs += '--delete' }
        $rsyncArgs += $wslSrc
        $rsyncArgs += "${target}:${remoteDir}/"
        wsl rsync @rsyncArgs
    } else {
        # Fallback: scp (kein automatisches Loeschen von Remotedateien)
        Write-Warning "WSL nicht gefunden – nutze scp. Geloeschte lokale Dateien bleiben auf dem Server."
        ssh $target "mkdir -p '$remoteDir'"
        scp -r "${localDir}\." "${target}:${remoteDir}/"
    }

    if ($LASTEXITCODE -ne 0) {
        Write-Error "Uebertragung fehlgeschlagen (Exit $LASTEXITCODE)."
        exit $LASTEXITCODE
    }
}

$repoRoot = Split-Path $PSScriptRoot

# === Deploy-Modi ===
switch ($Mode) {

    'skin' {
        Write-Host "Deploye Cavendish-Skin..." -ForegroundColor Cyan
        Sync-Dir "$repoRoot\mediawiki\skins\Cavendish" "$mwPath/skins/Cavendish" -delete $true
        Write-Host "Fertig." -ForegroundColor Green
    }

    'templates' {
        if (-not $projectPath) {
            Write-Error "DEPLOY_PROJECT_PATH muss in .deploy.env gesetzt sein."
            exit 1
        }
        Write-Host "Deploye Wiki-Templates..." -ForegroundColor Cyan
        Sync-Dir "$repoRoot\scripts\templates" "$projectPath/scripts/templates"
        Write-Host "Fertig." -ForegroundColor Green
    }

    'all' {
        Write-Host "Deploye Skin + Templates..." -ForegroundColor Cyan
        Sync-Dir "$repoRoot\mediawiki\skins\Cavendish" "$mwPath/skins/Cavendish" -delete $true
        if ($projectPath) {
            Sync-Dir "$repoRoot\scripts\templates" "$projectPath/scripts/templates"
        }
        Write-Host "Fertig." -ForegroundColor Green
    }

    'initial' {
        Write-Host "Erstinstallation – uebertraege MediaWiki-Core..." -ForegroundColor Yellow
        Write-Host "Das kann einige Minuten dauern." -ForegroundColor DarkGray

        $excludes = @(
            '--exclude=.git',
            '--exclude=vendor/',
            '--exclude=images/',
            '--exclude=cache/',
            '--exclude=LocalSettings.php'
        )

        if ($hasWsl) {
            $wslSrc = (ConvertTo-WslPath "$repoRoot\mediawiki") + '/'
            $rsyncArgs = @('-az', '--progress') + $excludes + @($wslSrc, "${target}:${mwPath}/")
            wsl rsync @rsyncArgs
        } else {
            Write-Warning "Fuer die Erstinstallation wird WSL empfohlen (grosse Datenmenge)."
            Write-Warning "Alternative: WinSCP GUI verwenden oder WSL installieren."
            exit 1
        }

        Write-Host ""
        Write-Host "Erstinstallation abgeschlossen." -ForegroundColor Green
        Write-Host ""
        Write-Host "Naechste Schritte auf dem Server:" -ForegroundColor Yellow
        Write-Host "  1. LocalSettings.php anlegen:"
        Write-Host "     Vorlage: mediawiki/LocalSettings.production.example.php"
        Write-Host "  2. Composer-Abhaengigkeiten installieren:"
        Write-Host "     cd $mwPath && composer install --no-dev"
        Write-Host "  3. Datenbank einrichten:"
        Write-Host "     php maintenance/run.php install ..."
        Write-Host "     oder: Dump importieren mit mysql -u user -p dbname < dump.sql"
        Write-Host "  4. SMW initialisieren:"
        Write-Host "     php maintenance/run.php setupStore"
    }
}
