posh-old.psm1

param(
    [switch] $debug = $false,
    [switch] $expose = $false
)
$isForwarding = $expose -eq $true

. "$PSScriptRoot\src\utils\events.ps1"

function Test-Privileges {
    $user = [Security.Principal.WindowsIdentity]::GetCurrent();
    (New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}

function Assert-Connection {
    Write-Host "`nChecking internet connection..."
    if (-not (Test-Connection 8.8.8.8 -ErrorAction SilentlyContinue -Quiet)) {
        Write-Output "`nNo internet connection.`nConnect to the internet, then try again.`n"
        exit
    }
}

if (-not (Test-Privileges)) {
    Write-Host "`nThis script must be run as an administrator.`nTry opening the server again from a PowerShell instance with administrator privileges.`n"
    exit
}

Write-Output "`nStarting Posh..."

$processParams = "$(if ($debug) { '-NoExit' } else { '-WindowStyle Hidden' }) -ExecutionPolicy Bypass"

$http = Start-Process -FilePath "powershell.exe" -ArgumentList "$processParams -File $PSScriptRoot\src\app.ps1" -PassThru

Receive-Event($env:EVENT_SERVER_READY)

$message = "`nServer started successfully.$(if ($isForwarding) { "`nExposing local server to internet..." })"

Write-Output $message
if ($isForwarding) {
    $logPath = "$env:TEMP\csetup_logs.log"
    $errPath = "$env:TEMP\csetup_error.log"
    
    if (Test-Path $logPath) { Remove-Item $logPath -Force }
    
    $forwarding = Start-Process -FilePath "powershell.exe" -ArgumentList "$processParams -Command `"Invoke-Command -ScriptBlock { ssh -o StrictHostKeyChecking=no -R 80:localhost:4000 serveo.net > $($logPath) } 2>$($errPath) `"" -PassThru

    do {
        if ($ticks++ -gt 20) {
            $err = (Get-Content -Path $errPath -ErrorAction SilentlyContinue -Raw)
            if ($err -and $err.Contains("Could not resolve hostname") -and $tries++ -lt 3) { 
                Assert-Connection
                $ticks = 0
            }
            else {
                Write-Output "`nThere was an error while trying to expose your local server to the internet.`nTry again in a few seconds...`nFor more details, check the logs in:`n$logPath`n$errPath`n+"
                Stop-Server
                exit
            }
        }
        Start-Sleep -Milliseconds 250
        $hasToken = (Get-Content -Path $logPath -ErrorAction SilentlyContinue) -match "https:\/\/([a-f0-9]+)\.serveo\.net" 
    } while (-not $hasToken)
    
    Write-Output "`nServer successfully exposed to internet."
    
    Write-Host "The URL is: $($matches[0])`nThe token is: $($matches[1])"
}