param(
    [string]$ServiceName = "QYZH.InteractiveMagazine.PrintWorker",
    [string]$DisplayName = "QYZH InteractiveMagazine PrintWorker",
    [string]$Description = "InteractiveMagazine automatic dot-code print worker.",
    [string]$PublishPath = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
)

$ErrorActionPreference = "Stop"

if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    throw "Please run this script in an elevated PowerShell window."
}

$exePath = Resolve-Path (Join-Path $PublishPath "QYZH.InteractiveMagazine.PrintWorker.exe")
$existing = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue

if ($existing) {
    if ($existing.Status -ne "Stopped") {
        Stop-Service -Name $ServiceName -Force
        $existing.WaitForStatus("Stopped", "00:00:30")
    }

    sc.exe delete $ServiceName | Out-Null
    Start-Sleep -Seconds 2
}

New-Service `
    -Name $ServiceName `
    -BinaryPathName "`"$exePath`"" `
    -DisplayName $DisplayName `
    -Description $Description `
    -StartupType Automatic

Start-Service -Name $ServiceName
Get-Service -Name $ServiceName
