$tempKeyPath = [System.IO.Path]::GetTempFileName()
$tempCertPath = [System.IO.Path]::GetTempFileName()
$tempPfxPath = [System.IO.Path]::GetTempFileName()

try
{
    $certificatePassword = [guid]::NewGuid().ToString().Replace("-", "")

    $sslPath = Join-Path $PSScriptRoot "OpenSSL"

    $Env:OPENSSL_CONF = "$($sslPath)/bin/openssl.cfg"
    
    $sslCommand = "$($sslPath)/bin/openssl.exe"
    try {
        if ($IsLinux) {
            $sslCommand = "openssl"
        }    
    }
    catch {
        # ignore, if not using powershell core #IsLinux is not defined
    }
    

    & $sslCommand req -new -newkey rsa:4096 -days 3650 -nodes -x509 -subj "/C=US/ST=MN/L=Minneapolis/O=Online/CN=identity" -keyout "$($tempKeyPath)" -out "$($tempCertPath)"
    & $sslCommand pkcs12 -export -in "$($tempCertPath)" -inkey "$($tempKeyPath)" -out "$($tempPfxPath)" -password pass:$certificatePassword 2>&1 | Out-Null

    $fileLength = (Get-Item $tempPfxPath).Length

    if ($fileLength -gt 0)
    {
        $pfxPath = Join-Path $PSScriptRoot "../.config/identity.pfx"
        
        $directory = Split-Path $pfxPath -Parent
        if (-not (Test-Path $directory)) {
            New-Item $directory -ItemType Directory
        }
        
        Write-Host "Writing pfx to $pfxPath"
        Copy-Item $tempPfxPath $pfxPath

        $envPath = Join-Path $PSScriptRoot "../.env"
        Write-Host "Updating $envPath with Environment__CertificatePassword=$certificatePassword"
        $envContent = Get-Content -Path $envPath

        $envContent = $envContent -replace '^Environment__CertificatePassword=.*', "Environment__CertificatePassword=$certificatePassword"

        Set-Content -Path $envPath -Value $envContent
    }
    else
    {
        Write-Output "Unexpected error occurred, unable to generate PFX file."

    }
}
finally
{
    Remove-Item $tempKeyPath
    Remove-Item $tempCertPath
    Remove-Item $tempPfxPath
}
