# Connect to remote PC and list files
$remoteHost = "192.168.1.191"
$remoteUser = "rob"
$remoteDir = "C:\Users\rob\Documents\Projects\Leanback_11"
$remoteTestDir = "C:\Users\rob\Documents\Projects\Leanback_11\test"
$scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path

# Check if OpenSSH is installed locally
Write-Host "Checking OpenSSH installation..." -ForegroundColor Yellow
if (-not (Get-WindowsCapability -Online -Name 'OpenSSH.Client~~~~0.0.1.0').State -eq 'Installed') {
    Write-Host "Installing OpenSSH Client..." -ForegroundColor Yellow
    Add-WindowsCapability -Online -Name 'OpenSSH.Client~~~~0.0.1.0'
}

# Test SSH connection first
Write-Host "Testing SSH connection..." -ForegroundColor Yellow
try {
    $testConnection = ssh -o BatchMode=no -o ConnectTimeout=5 "$remoteUser@$remoteHost" "powershell -ExecutionPolicy Bypass -Command `"echo 'Connection successful'`""
    if ($testConnection -eq 'Connection successful') {
        Write-Host "SSH connection test successful" -ForegroundColor Green
    }
} catch {
    Write-Host "SSH connection test failed. Please check:" -ForegroundColor Red
    Write-Host "1. OpenSSH Server is installed on the remote machine" -ForegroundColor Red
    Write-Host "2. SSH service is running on the remote machine" -ForegroundColor Red
    Write-Host "3. Firewall allows SSH connections (port 22)" -ForegroundColor Red
    Write-Host "4. Your credentials are correct" -ForegroundColor Red
    exit 1
}

# First, check if the directories exist and create them if they don't
Write-Host "Checking remote directories..." -ForegroundColor Yellow
$checkDirCommand = "powershell -ExecutionPolicy Bypass -Command `"if (-not (Test-Path '$remoteDir')) { New-Item -ItemType Directory -Path '$remoteDir' -Force }; if (-not (Test-Path '$remoteTestDir')) { New-Item -ItemType Directory -Path '$remoteTestDir' -Force }`""
ssh "$remoteUser@$remoteHost" $checkDirCommand

# Copy bginfo.ps1 to remote test directory
Write-Host "Copying bginfo.ps1 to remote test directory..." -ForegroundColor Yellow
$bginfoPath = Join-Path $scriptPath "test\bginfo.ps1"
if (Test-Path $bginfoPath) {
    $bginfoContent = Get-Content -Path $bginfoPath -Raw
    $bginfoContent = $bginfoContent -replace '"', '\"'
    $copyCommand = "powershell -ExecutionPolicy Bypass -Command `"Set-Content -Path '$remoteTestDir\bginfo.ps1' -Value '$bginfoContent'`""
    ssh "$remoteUser@$remoteHost" $copyCommand
} else {
    Write-Host "Warning: Could not find bginfo.ps1 at $bginfoPath" -ForegroundColor Yellow
}

# List files in the remote test directory
Write-Host "`nAvailable scripts in ${remoteTestDir}:" -ForegroundColor Green
try {
    $command = "powershell -ExecutionPolicy Bypass -Command `"Get-ChildItem -Path '$remoteTestDir' -Filter '*.ps1' | Select-Object Name, LastWriteTime | Format-Table -AutoSize`""
    $files = ssh "$remoteUser@$remoteHost" $command
    Write-Host $files
} catch {
    Write-Host "Failed to list files. Error: $_" -ForegroundColor Red
    exit 1
}

# Get user selection
$selection = Read-Host "`nEnter the number of the script you want to run (or 'q' to quit)"

if ($selection -eq 'q') {
    Write-Host "Exiting..." -ForegroundColor Yellow
    exit
}

# Get the selected file
try {
    $command = "powershell -ExecutionPolicy Bypass -Command `"`$files = Get-ChildItem -Path '$remoteTestDir' -Filter '*.ps1'; `$files[$selection - 1].FullName`""
    $selectedFile = ssh "$remoteUser@$remoteHost" $command
} catch {
    Write-Host "Failed to get selected file. Error: $_" -ForegroundColor Red
    exit 1
}

if ($selectedFile) {
    $scriptName = Split-Path $selectedFile -Leaf
    $date = Get-Date -Format "yyyy-MM-dd"
    $logFileName = "$date-$scriptName.log"
    $logPath = Join-Path $remoteTestDir $logFileName

    Write-Host "`nRunning ${selectedFile}..." -ForegroundColor Green
    Write-Host "Logging to ${logPath}" -ForegroundColor Yellow

    # Run the script and capture output
    try {
        $command = @"
        powershell -ExecutionPolicy Bypass -Command "
        Start-Transcript -Path '$logPath' -Force
        try {
            `$process = Start-Process powershell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File \"$selectedFile\"' -Verb RunAs -PassThru -Wait
            Write-Output \"`nProcess Exit Code: `$(`$process.ExitCode)\"
        }
        catch {
            Write-Output \"Error running script: `$_\" 
        }
        finally {
            Stop-Transcript
        }
        "
"@
        ssh "$remoteUser@$remoteHost" $command
    } catch {
        Write-Host "Failed to run script. Error: $_" -ForegroundColor Red
        exit 1
    }

    # Display the log contents
    Write-Host "`nLog contents:" -ForegroundColor Green
    try {
        $command = "powershell -ExecutionPolicy Bypass -Command `"Get-Content '$logPath'`""
        $logContents = ssh "$remoteUser@$remoteHost" $command
        Write-Host $logContents
    } catch {
        Write-Host "Failed to read log file. Error: $_" -ForegroundColor Red
    }

    Write-Host "`nLog file saved to: ${logPath}" -ForegroundColor Green
} else {
    Write-Host "Invalid selection" -ForegroundColor Red
} 