# Registers YarMenu Accounting in Windows "Installed apps" + Start menu search.
# Usage: powershell -ExecutionPolicy Bypass -File register_windows_app.ps1 -InstallDir "C:\...\YarMenu\Accounting"

param(
    [Parameter(Mandatory = $true)]
    [string]$InstallDir,
    [string]$Version = '',
    [string]$Publisher = 'YarMenu',
    [switch]$Unregister
)

$ErrorActionPreference = 'Stop'

$AppId = 'B9E4D3F2-0C5E-5B30-9F2D-8E7C6B5A4F3E'
$DisplayName = 'YarMenu Accounting'
$ExeName = 'yarmenu_accounting.exe'
$UninstallRegPath = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\$AppId"
$StartMenuDir = Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs\YarMenu Accounting'
$DesktopLnk = Join-Path ([Environment]::GetFolderPath('Desktop')) 'YarMenu Accounting.lnk'

function Get-InstallVersion {
    param([string]$Dir)
    $versionFile = Join-Path $Dir 'version.txt'
    if (Test-Path $versionFile) {
        return (Get-Content $versionFile -Raw).Trim()
    }
    return '0.0.0'
}

function Write-UninstallScript {
    param([string]$Dir)
    $path = Join-Path $Dir 'uninstall.ps1'
    @"
# YarMenu Accounting uninstaller
`$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Windows.Forms
`$confirm = [System.Windows.Forms.MessageBox]::Show(
    'Remove YarMenu Accounting from this PC?',
    'YarMenu Accounting',
    [System.Windows.Forms.MessageBoxButtons]::YesNo,
    [System.Windows.Forms.MessageBoxIcon]::Question
)
if (`$confirm -ne [System.Windows.Forms.DialogResult]::Yes) { exit 0 }

`$appId = '$AppId'
`$reg = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\`$appId"
`$startMenu = '$($StartMenuDir.Replace("'", "''"))'
`$desktop = '$($DesktopLnk.Replace("'", "''"))'
`$installDir = '$($Dir.Replace("'", "''"))'

if (Test-Path `$reg) { Remove-Item `$reg -Recurse -Force }
if (Test-Path `$startMenu) { Remove-Item `$startMenu -Recurse -Force }
if (Test-Path `$desktop) { Remove-Item `$desktop -Force }
if (Test-Path `$installDir) { Remove-Item `$installDir -Recurse -Force }

[System.Windows.Forms.MessageBox]::Show(
    'YarMenu Accounting was removed.',
    'YarMenu Accounting',
    [System.Windows.Forms.MessageBoxButtons]::OK,
    [System.Windows.Forms.MessageBoxIcon]::Information
) | Out-Null
"@ | Set-Content -Path $path -Encoding UTF8
    return $path
}

function New-Shortcut {
    param(
        [string]$LinkPath,
        [string]$TargetExe,
        [string]$WorkDir,
        [string]$Description
    )
    $parent = Split-Path $LinkPath -Parent
    if (-not (Test-Path $parent)) {
        New-Item -ItemType Directory -Path $parent -Force | Out-Null
    }
    $wsh = New-Object -ComObject WScript.Shell
    $sc = $wsh.CreateShortcut($LinkPath)
    $sc.TargetPath = $TargetExe
    $sc.WorkingDirectory = $WorkDir
    $sc.Description = $Description
    $sc.IconLocation = "$TargetExe,0"
    $sc.Save()
}

function Register-YarMenuAccounting {
    param([string]$Dir, [string]$Ver)
    $exe = Join-Path $Dir $ExeName
    if (-not (Test-Path $exe)) {
        throw "Not found: $exe"
    }

    $uninstallScript = Write-UninstallScript -Dir $Dir
    $sizeKb = [int]((Get-ChildItem -Path $Dir -Recurse -File | Measure-Object -Property Length -Sum).Sum / 1KB)

    if (-not (Test-Path $UninstallRegPath)) {
        New-Item -Path $UninstallRegPath -Force | Out-Null
    }

    $uninstallCmd = "powershell.exe -NoProfile -ExecutionPolicy Bypass -File `"$uninstallScript`""
    Set-ItemProperty -Path $UninstallRegPath -Name DisplayName -Value $DisplayName
    Set-ItemProperty -Path $UninstallRegPath -Name DisplayVersion -Value $Ver
    Set-ItemProperty -Path $UninstallRegPath -Name Publisher -Value $Publisher
    Set-ItemProperty -Path $UninstallRegPath -Name InstallLocation -Value $Dir
    Set-ItemProperty -Path $UninstallRegPath -Name DisplayIcon -Value "$exe,0"
    Set-ItemProperty -Path $UninstallRegPath -Name UninstallString -Value $uninstallCmd
    Set-ItemProperty -Path $UninstallRegPath -Name QuietUninstallString -Value $uninstallCmd
    Set-ItemProperty -Path $UninstallRegPath -Name InstallDate -Value (Get-Date -Format 'yyyyMMdd')
    Set-ItemProperty -Path $UninstallRegPath -Name NoModify -Value 1 -Type DWord
    Set-ItemProperty -Path $UninstallRegPath -Name NoRepair -Value 1 -Type DWord
    Set-ItemProperty -Path $UninstallRegPath -Name EstimatedSize -Value $sizeKb -Type DWord
    Set-ItemProperty -Path $UninstallRegPath -Name URLInfoAbout -Value 'https://yarmenu.com'

    New-Shortcut -LinkPath (Join-Path $StartMenuDir 'YarMenu Accounting.lnk') `
        -TargetExe $exe -WorkDir $Dir -Description 'YarMenu Accounting'
}

function Unregister-YarMenuAccounting {
    if (Test-Path $UninstallRegPath) {
        Remove-Item $UninstallRegPath -Recurse -Force
    }
    if (Test-Path $StartMenuDir) {
        Remove-Item $StartMenuDir -Recurse -Force
    }
}

$InstallDir = (Resolve-Path $InstallDir).Path
if ([string]::IsNullOrWhiteSpace($Version)) {
    $Version = Get-InstallVersion -Dir $InstallDir
}

if ($Unregister) {
    Unregister-YarMenuAccounting
} else {
    Register-YarMenuAccounting -Dir $InstallDir -Ver $Version
}
