$ErrorActionPreference= 'Stop'

$rustdesk_pw=(-join ((65..90) + (97..122) + (48..57) | Get-Random -Count 12 | % {[char]$_}))
$rustdesk_cfg="Qfi0TT1YGVJZXMhNWUFNUbudXN5h2bRdUdVdHVrZlcDFWMUNUNyoVa5FVNEREViojI5V2aiwiInJ3buMnbkt2Y1RmL0NXdylnbhlXbv8iOzBHd0hmI6ISawFmIsIiI6ISehxWZyJCLigTMuATNx4iNyIjLyMTMiojI0N3boJye"
$installerName="rustdesk-1.4.6-x86_64.exe"
$downloadUrl="https://github.com/rustdesk/rustdesk/releases/download/1.4.6/rustdesk-1.4.6-x86_64.exe"

if (-Not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
{
    Start-Process PowerShell -Verb RunAs -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`""
    Exit
}

$workdir = Split-Path -Parent $PSCommandPath
Set-Location $workdir

if (!(Test-Path $installerName))
{
    Invoke-WebRequest $downloadUrl -OutFile $installerName
}

Start-Process ".\$installerName" --silent-install -Wait
Start-Sleep -Seconds 12

$serviceName = 'Rustdesk'
$service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
if ($null -eq $service)
{
    Set-Location "$env:ProgramFiles\RustDesk"
    Start-Process ".\rustdesk.exe" --install-service -Wait
    Start-Sleep -Seconds 10
    $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
}

while ($service.Status -ne 'Running')
{
    Start-Service $serviceName
    Start-Sleep -Seconds 3
    $service.Refresh()
}

Set-Location "$env:ProgramFiles\RustDesk"
.\rustdesk.exe --config $rustdesk_cfg
.\rustdesk.exe --password $rustdesk_pw
$rustdesk_id = .\rustdesk.exe --get-id

Write-Output "----------------------------------------"
Write-Output "RustDesk instalado y configurado"
Write-Output "ID: $rustdesk_id"
Write-Output "Password: $rustdesk_pw"
Write-Output "----------------------------------------"
pause
