$ErrorActionPreference = 'Stop'

$configPath = Join-Path $env:APPDATA 'obs-studio\plugin_config\obs-websocket\config.json'
$configDirectory = Split-Path $configPath
New-Item $configDirectory -ItemType Directory -Force | Out-Null

if (Test-Path $configPath) {
    $config = Get-Content $configPath -Raw | ConvertFrom-Json
} else {
    $config = [pscustomobject]@{}
}

function Set-ConfigValue([string]$Name, $Value) {
    if ($config.PSObject.Properties.Name -contains $Name) {
        $config.$Name = $Value
    } else {
        $config | Add-Member -NotePropertyName $Name -NotePropertyValue $Value
    }
}

Set-ConfigValue 'alerts_enabled' $false
Set-ConfigValue 'auth_required' $true
Set-ConfigValue 'first_load' $false
Set-ConfigValue 'server_enabled' $true

if (!($config.PSObject.Properties.Name -contains 'server_port') -or $config.server_port -notin 1..65535) {
    Set-ConfigValue 'server_port' 4455
}
if (!($config.PSObject.Properties.Name -contains 'server_password') -or [string]::IsNullOrWhiteSpace($config.server_password)) {
    $bytes = New-Object byte[] 32
    [Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes)
    Set-ConfigValue 'server_password' ([Convert]::ToBase64String($bytes))
}

$json = $config | ConvertTo-Json
[IO.File]::WriteAllText($configPath, $json, [Text.UTF8Encoding]::new($false))
