#!/usr/bin/env pwsh

param(
    [string]$licenseName,
    [string]$licenseKey,
    [string]$licenseDate,
    [bool]$checkForUpdates,
    [string]$language,
    [bool]$allUsers = $false,
    [switch]$help
)

function Show-Usage {
    Write-Host ""
    Write-Host "Usage:"
    Write-Host "  mindomoinit.ps1 -licenseName <string> -licenseKey <string> -licenseDate <YYYY-MM-DD-TYPE> "
    Write-Host '                  -checkForUpdates <$true|$false> -language <code> [-allUsers <$true|$false>]'
    Write-Host ""
    Write-Host "Parameters:"
    Write-Host "  -licenseName        REQUIRED  The user's license name"
    Write-Host "  -licenseKey         REQUIRED  The user's license key"
    Write-Host "  -licenseDate        REQUIRED  Format: YYYY-MM-DD-TYPE (e.g. 2025-01-31-E)"
    Write-Host "  -checkForUpdates    REQUIRED  true or false"
    Write-Host "  -language           REQUIRED  Language code (e.g. en, fr, de)"
    Write-Host "  -allUsers           OPTIONAL  If true, writes init.json to Program Files"
    Write-Host ""
    Write-Host "Examples:"
    Write-Host "  Per-user install:"
    Write-Host '    .\mindomoinit.ps1 -licenseName "John Doe" -licenseKey "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX" -licenseDate "2025-01-31-E" -checkForUpdates $true -language "en"'
    Write-Host ""
    Write-Host "  All-users install (run as administrator):"
    Write-Host '    .\mindomoinit.ps1 -licenseName "John Doe" -licenseKey "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX" -licenseDate "2025-01-31-E" -checkForUpdates $true -language "en" -allUsers $true'
    Write-Host ""
}

function Test-IsAdmin {
    $currentIdentity  = [Security.Principal.WindowsIdentity]::GetCurrent()
    $principal        = New-Object Security.Principal.WindowsPrincipal($currentIdentity)
    return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}

# Show help if requested
if ($help -or $args -contains "-?" -or $args -contains "--help") {
    Show-Usage
    exit 0
}

# Validate required parameters
if (-not $licenseName -or -not $licenseKey -or -not $licenseDate -or
    $checkForUpdates -eq $null -or -not $language) {

    Write-Host "Error: Missing required parameters." -ForegroundColor Red
    Show-Usage
    exit 1
}

# Validate licenseDate format: YYYY-MM-DD-TYPE
$parts = $licenseDate -split '-'
if ($parts.Count -lt 4 -or $parts[0] -notmatch '^\d{4}$' -or
    $parts[1] -notmatch '^\d{2}$' -or $parts[2] -notmatch '^\d{2}$') {

    Write-Host "Error: licenseDate must be in format: YYYY-MM-DD-E (e.g. 2025-01-31-E)" -ForegroundColor Red
    Show-Usage
    exit 1
}

# Extract values
$licenseExpiry = ($parts[0..2] -join '-')
$licenseType   = $parts[3]

# If allUsers, require admin
if ($allUsers) {
    if (-not (Test-IsAdmin)) {
        Write-Host "Error: -allUsers was specified, but the script is not running with administrator privileges." -ForegroundColor Red
        Write-Host "Please run PowerShell as Administrator and try again."
        exit 1
    }
}

# Determine destination directory
if ($allUsers) {
    # Matches NSIS $PROGRAMFILES
    $mindomoDir = Join-Path -Path $env:ProgramFiles -ChildPath "Mindomo"
} else {
    $mindomoDir = Join-Path -Path $env:APPDATA -ChildPath "Mindomo"
}

# Create directory if missing
if (-not (Test-Path -LiteralPath $mindomoDir)) {
    New-Item -ItemType Directory -Path $mindomoDir -Force | Out-Null
}

$initFile = "init.json"
$initFullPath = Join-Path -Path $mindomoDir -ChildPath $initFile

# Build JSON structure
$data = [ordered]@{
    license = [ordered]@{
        expiryDate = $licenseExpiry
        key        = $licenseKey
        name       = $licenseName
        type       = $licenseType
    }
    userSettings = [ordered]@{
        acceptedLicense   = $true
        showWelcomeScreen = $false
        checkForUpdates   = $checkForUpdates
    }
    appData = [ordered]@{
        selectedLanguage = $language
    }
}

# Convert to JSON
$json = $data | ConvertTo-Json -Depth 5

# Write JSON as UTF-8 **without BOM**, consistent across PowerShell versions
$utf8NoBom = New-Object System.Text.UTF8Encoding($false)
[System.IO.File]::WriteAllText($initFullPath, $json, $utf8NoBom)

Write-Host "init.json written to: $initFullPath"
