# deploy.ps1
# Deploys the fixed TestDataDB application to AD2 (192.168.0.6).
#
# Copies files via SCP, installs dependencies, sets up the Windows service,
# and installs the backup scheduled task.
#
# Must be run from the directory containing the fixed files.

$ErrorActionPreference = 'Stop'

$RemoteHost   = '192.168.0.6'
$RemoteUser   = 'INTRANET\sysadmin'
$RemotePass   = 'Paper123!@#'
$RemotePath   = 'C:\Shares\testdatadb'
$SshExe       = 'C:\Windows\System32\OpenSSH\ssh.exe'
$ScpExe       = 'C:\Windows\System32\OpenSSH\scp.exe'
$LocalDir     = $PSScriptRoot

# Credentials for SSH - set up sshpass-equivalent via environment
# Note: For automated deployment, the SSH key should be pre-configured.
# This script uses password-based auth via the ssh client.

$SshTarget = "${RemoteUser}@${RemoteHost}"

function Invoke-RemoteCommand {
    param([string]$Command)
    Write-Host "[INFO] Remote: $Command"
    & $SshExe $SshTarget $Command
    if ($LASTEXITCODE -ne 0) {
        Write-Host "[ERROR] Remote command failed with exit code $LASTEXITCODE"
        exit 1
    }
}

function Copy-ToRemote {
    param([string]$LocalFile, [string]$RemoteDir)
    $remoteDest = "${SshTarget}:`"${RemoteDir}`""
    Write-Host "[INFO] Copying $LocalFile -> $RemoteDir"
    & $ScpExe $LocalFile $remoteDest
    if ($LASTEXITCODE -ne 0) {
        Write-Host "[ERROR] SCP failed for $LocalFile"
        exit 1
    }
}

Write-Host '========================================'
Write-Host 'TestDataDB Deployment to AD2'
Write-Host '========================================'
Write-Host ''

# -----------------------------------------------------------------------
# Step 1: Ensure remote directories exist
# -----------------------------------------------------------------------
Write-Host '[STEP 1] Creating remote directories...'
Invoke-RemoteCommand "if not exist `"${RemotePath}\routes`" mkdir `"${RemotePath}\routes`""
Invoke-RemoteCommand "if not exist `"${RemotePath}\logs`" mkdir `"${RemotePath}\logs`""
Invoke-RemoteCommand "if not exist `"${RemotePath}\backups`" mkdir `"${RemotePath}\backups`""

# -----------------------------------------------------------------------
# Step 2: Stop existing node process / service
# -----------------------------------------------------------------------
Write-Host ''
Write-Host '[STEP 2] Stopping existing processes...'
# Try stopping the service first (may not exist yet)
& $SshExe $SshTarget "net stop TestDataDB 2>nul & echo Service stop attempted"
# Kill any lingering node processes running server.js
& $SshExe $SshTarget "taskkill /F /FI `"IMAGENAME eq node.exe`" 2>nul & echo Process kill attempted"
Write-Host '[OK] Existing processes stopped.'

# -----------------------------------------------------------------------
# Step 3: Copy files to remote
# -----------------------------------------------------------------------
Write-Host ''
Write-Host '[STEP 3] Copying files to AD2...'

$filesToCopy = @(
    @{ Local = "$LocalDir\server.js";               Remote = $RemotePath },
    @{ Local = "$LocalDir\package.json";             Remote = $RemotePath },
    @{ Local = "$LocalDir\install-service.js";       Remote = $RemotePath },
    @{ Local = "$LocalDir\uninstall-service.js";     Remote = $RemotePath },
    @{ Local = "$LocalDir\backup-db.ps1";            Remote = $RemotePath },
    @{ Local = "$LocalDir\install-backup-task.ps1";  Remote = $RemotePath },
    @{ Local = "$LocalDir\routes\api.js";            Remote = "$RemotePath\routes" }
)

foreach ($file in $filesToCopy) {
    Copy-ToRemote -LocalFile $file.Local -RemoteDir $file.Remote
}

Write-Host '[OK] All files copied.'

# -----------------------------------------------------------------------
# Step 4: Install npm dependencies
# -----------------------------------------------------------------------
Write-Host ''
Write-Host '[STEP 4] Installing npm dependencies...'
Invoke-RemoteCommand "cd /d `"${RemotePath}`" && npm install --production"
Write-Host '[OK] Dependencies installed.'

# -----------------------------------------------------------------------
# Step 5: Uninstall old service (if present) and install new one
# -----------------------------------------------------------------------
Write-Host ''
Write-Host '[STEP 5] Installing Windows service...'
# Uninstall first to ensure clean state
& $SshExe $SshTarget "cd /d `"${RemotePath}`" && node uninstall-service.js 2>nul"
Start-Sleep -Seconds 3
Invoke-RemoteCommand "cd /d `"${RemotePath}`" && node install-service.js"
Write-Host '[OK] Windows service installed.'

# -----------------------------------------------------------------------
# Step 6: Install backup scheduled task
# -----------------------------------------------------------------------
Write-Host ''
Write-Host '[STEP 6] Installing backup scheduled task...'
Invoke-RemoteCommand "powershell -NoProfile -ExecutionPolicy Bypass -File `"${RemotePath}\install-backup-task.ps1`""
Write-Host '[OK] Backup task installed.'

# -----------------------------------------------------------------------
# Step 7: Verify service is running
# -----------------------------------------------------------------------
Write-Host ''
Write-Host '[STEP 7] Verifying service status...'
Start-Sleep -Seconds 5
& $SshExe $SshTarget "sc query TestDataDB"

Write-Host ''
Write-Host '========================================'
Write-Host '[OK] Deployment complete.'
Write-Host "[INFO] Service: TestDataDB on $RemoteHost"
Write-Host "[INFO] URL: http://${RemoteHost}:3000"
Write-Host "[INFO] Logs: ${RemotePath}\logs\"
Write-Host "[INFO] Backups: ${RemotePath}\backups\ (daily at 2 AM)"
Write-Host '========================================'
