Hetzner.ps1

function Install-HeztnerCli {

  if (-Not(Get-Command "hcloud.exe" -ErrorAction SilentlyContinue)) { 
    scoop install hcloud
    hcloud completion powershell | Out-String | Invoke-Expression
  }
}

function New-Hetzner {
  param(

    [Parameter(Mandatory = $true)]
    [String] $name,
    [String] $type = "cx11" # cx32
  )

  Install-HeztnerCli

  #### Activate context

  $active = hcloud context active
  if (-Not($active)) {
    Write-Host "Active context not found"
    Write-Host "Visit the Hetzner Cloud Console at https://console.hetzner.cloud/, select your project, and create a new API token"
    $project = Read-Host -Prompt "Project"
    Write-Host "Copy and paste your token (it will not be showed) and press enter"
    hcloud context create $project
  }

  ##### Create server

  $servers = hcloud.exe server list -o json | ConvertFrom-Json
  $server = $servers | Where-Object { $_.name -eq $name }
  if (-Not($server)) {
    Write-Host "Creating server ${name}"
    $key_path = Get-SshKey -Public
    hcloud ssh-key create --name dev --public-key-from-file $key_path
    hcloud server create --name $name --image ubuntu-24.04 --type $type --ssh-key dev # -o json
  }

  ##### Config server

  $ip = hcloud server ip $name

  $command = "adduser box; usermod -aG sudo box; mkdir -p /home/box/.ssh; cp .ssh/authorized_keys /home/box/.ssh/authorized_keys; chown -R box:box /home/box/.ssh;"

  # TODO wait server responsive; pwsh ask password or ...
  Connect-Ssh $ip $command | Write-Host
  

  ##### VS Code

  $hostList = Get-ConfigHostList
  if (-Not($hostList.ContainsKey($name))) {
    $hostList = Add-ConfigHostToList -HostList $hostList -HostName $name -HostValues @{
      identityfile          = $sshKey
      hostname              = $ip
      user                  = "box"
      StrictHostKeyChecking = "no"
      UserKnownHostsFile    = "/dev/null"
    }
    Set-ConfigHostList $hostList
  }
  else {
    # TODO check IP
  }

  # https://code.visualstudio.com/docs/remote/troubleshooting#_connect-to-a-remote-host-from-the-terminal
  # TODO move to Code.ps1
  code --folder-uri "vscode-remote://ssh-remote+${name}/home/box"
}

function Remove-Hetzner {
  param(
    [Parameter(Position = 0, mandatory = $true)]
    [string] $name
  )

  Install-HeztnerCli

  hcloud server delete $name
}