# =============================================================
#  AMA EDU - Script de synchronisation LOCAL -> VPS
#  PowerShell natif Windows
# =============================================================

$ErrorActionPreference = "SilentlyContinue"

# -- Configuration ---------------------------------------------
$LOCAL_URL   = "http://localhost"
$VPS_HOST    = "161.97.128.28"
$VPS_USER    = "amaedu"
$VPS_SSH_KEY = "$env:USERPROFILE\.ssh\amaedu_sync_key"
$VPS_SCRIPT  = "/opt/amaedu/sync_import.sh"
$VPS_UPLOAD  = "/tmp"

$DB_HOST      = "localhost"
$DB_PORT      = "3306"
$DB_USER      = "root"
$DB_PASS      = ""
$DB_NAME      = "bethesda"

$MYSQLDUMP   = "C:\xampp\mysql\bin\mysqldump.exe"
if (-not (Test-Path $MYSQLDUMP)) {
    $found = Get-Command mysqldump -ErrorAction SilentlyContinue
    if ($found) { $MYSQLDUMP = $found.Source }
}

$ScriptRoot  = Split-Path -Parent $MyInvocation.MyCommand.Path
$LogDir      = "$ScriptRoot\..\logs"
$DumpDir     = "$ScriptRoot\..\dumps"
$LogFile     = "$LogDir\sync.log"

New-Item -ItemType Directory -Path $LogDir  -Force | Out-Null
New-Item -ItemType Directory -Path $DumpDir -Force | Out-Null

$Date        = Get-Date -Format "yyyyMMdd_HHmmss"
$DumpFile    = "dump_$Date.sql"
$ArchiveFile = "$DumpFile.gz"
$DumpPath    = "$DumpDir\$DumpFile"
$ArchivePath = "$DumpDir\$ArchiveFile"

# -- Fonctions -------------------------------------------------
function Log($msg) {
    $line = "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] $msg"
    Add-Content -Path $LogFile -Value $line -Encoding UTF8
    Write-Host $line -ForegroundColor Cyan
}
function LogOk($msg) {
    $line = "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] OK  $msg"
    Add-Content -Path $LogFile -Value $line -Encoding UTF8
    Write-Host $line -ForegroundColor Green
}
function LogErr($msg) {
    $line = "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] ERR $msg"
    Add-Content -Path $LogFile -Value $line -Encoding UTF8
    Write-Host $line -ForegroundColor Red
}
function Abort($msg) {
    LogErr $msg
    try {
        Invoke-WebRequest -Uri "$LOCAL_URL/admin/sync/maintenance/off" -Method POST -UseBasicParsing | Out-Null
    } catch {}
    Write-Host ""
    Write-Host "  SYNCHRONISATION ECHOUEE" -ForegroundColor Red
    Write-Host "  Consultez : logs\sync.log" -ForegroundColor Red
    exit 1
}
function Compress-Gzip($inputPath, $outputPath) {
    $in  = [System.IO.File]::OpenRead($inputPath)
    $out = [System.IO.File]::Create($outputPath)
    $gz  = New-Object System.IO.Compression.GZipStream($out, [System.IO.Compression.CompressionMode]::Compress)
    $in.CopyTo($gz)
    $gz.Close()
    $out.Close()
    $in.Close()
}

# -- Debut -----------------------------------------------------
Clear-Host
Write-Host ""
Write-Host "  AMA EDU - SYNCHRONISATION EN COURS" -ForegroundColor Cyan
Write-Host "  =====================================" -ForegroundColor Cyan
Log "Demarrage synchronisation ($Date)"

# -- Etape 1 : Verifications -----------------------------------
Write-Host ""
Write-Host "-- Etape 1 : Verifications" -ForegroundColor Yellow

if (-not (Test-Connection -ComputerName "8.8.8.8" -Count 1 -Quiet)) {
    Abort "Pas de connexion internet."
}
LogOk "Connexion internet OK"

if (-not (Test-Path $MYSQLDUMP)) {
    Abort "mysqldump introuvable : $MYSQLDUMP"
}
LogOk "mysqldump OK : $MYSQLDUMP"

if (-not (Get-Command ssh -ErrorAction SilentlyContinue)) {
    Abort "OpenSSH non trouve. Verifiez l'installation."
}
LogOk "OpenSSH OK"

& ssh -i $VPS_SSH_KEY -o ConnectTimeout=10 -o BatchMode=yes -o StrictHostKeyChecking=accept-new "$VPS_USER@$VPS_HOST" "echo ok" 2>&1 | Out-Null
if ($LASTEXITCODE -ne 0) {
    Abort "Impossible de se connecter au VPS ($VPS_HOST)."
}
LogOk "Connexion VPS OK"

# -- Etape 2 : Maintenance ON ----------------------------------
Write-Host ""
Write-Host "-- Etape 2 : Maintenance ON" -ForegroundColor Yellow
try {
    $r = Invoke-WebRequest -Uri "$LOCAL_URL/admin/sync/maintenance/on" -Method POST -UseBasicParsing -TimeoutSec 10
    LogOk "Maintenance activee (HTTP $($r.StatusCode))"
} catch {
    Log "Maintenance HTTP non disponible (on continue)"
}

# -- Etape 3 : Dump MySQL --------------------------------------
Write-Host ""
Write-Host "-- Etape 3 : Dump MySQL" -ForegroundColor Yellow
Log "Demarrage mysqldump..."

$env:MYSQL_PWD = $DB_PASS
& $MYSQLDUMP --single-transaction --routines --triggers --events -h $DB_HOST -P $DB_PORT -u $DB_USER $DB_NAME | Out-File -FilePath $DumpPath -Encoding utf8

if ($LASTEXITCODE -ne 0 -or -not (Test-Path $DumpPath) -or (Get-Item $DumpPath).Length -eq 0) {
    Abort "Echec du dump MySQL. Verifiez les identifiants DB."
}
LogOk "Dump cree : $DumpFile ($([math]::Round((Get-Item $DumpPath).Length / 1MB, 2)) MB)"

# -- Etape 4 : Compression -------------------------------------
Write-Host ""
Write-Host "-- Etape 4 : Compression" -ForegroundColor Yellow
Log "Compression en cours..."

Add-Type -AssemblyName System.IO.Compression.FileSystem
Compress-Gzip -inputPath $DumpPath -outputPath $ArchivePath

if (-not (Test-Path $ArchivePath) -or (Get-Item $ArchivePath).Length -eq 0) {
    Abort "Echec de la compression."
}
Remove-Item $DumpPath -Force
LogOk "Archive creee : $ArchiveFile ($([math]::Round((Get-Item $ArchivePath).Length / 1KB, 1)) KB)"

# -- Etape 5 : Upload SCP --------------------------------------
Write-Host ""
Write-Host "-- Etape 5 : Upload vers VPS" -ForegroundColor Yellow
Log "Upload SCP en cours..."

& scp -i $VPS_SSH_KEY -o ConnectTimeout=30 -o StrictHostKeyChecking=accept-new $ArchivePath "${VPS_USER}@${VPS_HOST}:${VPS_UPLOAD}/${ArchiveFile}" 2>&1 | Out-Null

if ($LASTEXITCODE -ne 0) {
    Abort "Echec de l'upload SCP."
}
LogOk "Fichier envoye au serveur"

# -- Etape 6 : Import VPS --------------------------------------
Write-Host ""
Write-Host "-- Etape 6 : Import sur le VPS" -ForegroundColor Yellow
Log "Lancement sync_import.sh sur le VPS..."

$vpsOutput = & ssh -i $VPS_SSH_KEY -o ConnectTimeout=60 -o StrictHostKeyChecking=accept-new "$VPS_USER@$VPS_HOST" "bash $VPS_SCRIPT $ArchiveFile" 2>&1
Add-Content -Path $LogFile -Value $vpsOutput -Encoding UTF8

if ($LASTEXITCODE -ne 0) {
    Abort "Echec import VPS : $vpsOutput"
}
LogOk "Import VPS reussi"

# -- Etape 7 : Maintenance OFF ---------------------------------
Write-Host ""
Write-Host "-- Etape 7 : Maintenance OFF" -ForegroundColor Yellow
try {
    Invoke-WebRequest -Uri "$LOCAL_URL/admin/sync/maintenance/off" -Method POST -UseBasicParsing -TimeoutSec 10 | Out-Null
    LogOk "Maintenance desactivee"
} catch {
    Log "Maintenance OFF : $_"
}

# -- Nettoyage -------------------------------------------------
Get-ChildItem -Path $DumpDir -Filter "dump_*.sql.gz" |
    Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } |
    Remove-Item -Force
Log "Nettoyage archives effectue"

# -- Succes ----------------------------------------------------
LogOk "Synchronisation terminee avec succes"
Write-Host ""
Write-Host "  =====================================" -ForegroundColor Green
Write-Host "  OK - SYNCHRONISATION REUSSIE" -ForegroundColor Green
Write-Host "  =====================================" -ForegroundColor Green
Write-Host ""
exit 0