# Define the path to the config file (adjust the path as needed)
$configFilePath = "$PSScriptRoot\config.ini"

# Function to create the config file if it doesn't exist
function Create-ConfigFile {
    param (
        [string]$filePath
    )
    
    Write-Host "Configuration file not found. Let's create one."

    $ip = Read-Host "Enter the IP address of the remote machine"
    $username = Read-Host "Enter the username"
    $password = Read-Host "Enter the password"

    $configContent = @"
[Connection]
ip = $ip
username = $username
password = $password
"@

    $configContent | Out-File -FilePath $filePath
    Write-Host "Configuration file created at $filePath"
}

# Function to read the config file and get values
function Get-ConfigValue {
    param (
        [string]$section,
        [string]$key
    )
    $ini = Get-Content $configFilePath | Out-String
    $ini = $ini -replace '^\s*;.*$', '' # Remove comments
    $ini = $ini -replace '^\s*#.*$', '' # Remove comments
    $ini = $ini -replace '\s*=\s*', '=' # Remove spaces around equal sign

    $sectionData = ($ini -split "\r?\n" -replace '^\[([^\]]+)\]\s*$', '$1' -ne $section) -split "\r?\n"
    foreach ($line in $sectionData) {
        if ($line -match "^\s*$key\s*=\s*(.*)$") {
            return $matches[1]
        }
    }
}

# Check if the config file exists, if not, prompt user to create it
if (-not (Test-Path -Path $configFilePath)) {
    Create-ConfigFile -filePath $configFilePath
}

# Read config values
$ip = Get-ConfigValue -section "Connection" -key "ip"
$username = Get-ConfigValue -section "Connection" -key "username"
$password = Get-ConfigValue -section "Connection" -key "password"

# Convert the plain password to a secure string for further use
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force

# Create the local directory if it doesn't exist
$remotePath = "/root/handshakes"  # You can make this dynamic as well
$localFolder = "$([Environment]::GetFolderPath('Desktop'))\$([System.IO.Path]::GetFileName($remotePath))"

if (-not (Test-Path -Path $localFolder)) {
    New-Item -ItemType Directory -Path $localFolder | Out-Null
}

# Construct the SCP command using the password and SSH command to avoid password prompt
$scpCommand = "scp -o PreferredAuthentications=password -o PubkeyAuthentication=no ${username}@${ip}:${remotePath} ${localFolder}"
$sshCommand = "ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no ${username}@${ip} sudo rm -rf ${remotePath}"

# Execute the SCP command by passing the password through a pipeline
$processInfo = New-Object System.Diagnostics.ProcessStartInfo
$processInfo.FileName = "cmd.exe"
$processInfo.RedirectStandardInput = $true
$processInfo.RedirectStandardOutput = $true
$processInfo.RedirectStandardError = $true
$processInfo.UseShellExecute = $false
$processInfo.Arguments = "/c $scpCommand"
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $processInfo
$process.Start() | Out-Null

# Pass the password to the command
$process.StandardInput.WriteLine($password)
$process.StandardInput.Close()

$process.WaitForExit()

# Check if the SCP transfer was successful
if ($process.ExitCode -eq 0) {
    # Execute the SSH command by passing the password through a pipeline
    $processInfo.Arguments = "/c $sshCommand"
    $process = New-Object System.Diagnostics.Process
    $process.StartInfo = $processInfo
    $process.Start() | Out-Null

    # Pass the password to the command
    $process.StandardInput.WriteLine($password)
    $process.StandardInput.Close()

    $process.WaitForExit()
    
    Write-Host "Files transferred and removed from the remote machine successfully."
} else {
    Write-Host "SCP transfer failed. Files were not removed from the remote machine."
}

# Clear the plain password from memory
$securePassword = $null
