param(
  [string]$ServicePath = "$PSScriptRoot\hyper_tunnel_service.exe"
)

$ErrorActionPreference = "Stop"
$serviceName = "HyperTunnelService"
$resolvedPath = (Resolve-Path $ServicePath).Path

if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
  throw "Run this script from an elevated PowerShell session."
}

$existing = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
if ($existing) {
  Stop-Service -Name $serviceName -ErrorAction SilentlyContinue
  sc.exe delete $serviceName | Out-Null
  Start-Sleep -Seconds 1
}

New-Service `
  -Name $serviceName `
  -DisplayName "Hyper Tunnel Service" `
  -Description "Runs sing-box TUN for Hyper Client with elevated routing and DNS permissions." `
  -BinaryPathName "`"$resolvedPath`"" `
  -StartupType Automatic | Out-Null

Start-Service -Name $serviceName
Get-Service -Name $serviceName
