param(
  [Parameter(Mandatory = $true)] [string] $BuildDir,
  [string] $TenantId = 'c94051e5-a6c6-4068-bb5f-6e67e604afa0',
  [string] $ClientId = '169c9e2d-bfb6-4783-89b8-f5c863922972',
  [string] $CertificatePath = (Join-Path $env:LOCALAPPDATA 'Linekerpandi\SmartCut64\Signing\smartcut64-release-auth.pfx'),
  [string] $ProtectedPasswordPath = (Join-Path $env:LOCALAPPDATA 'Linekerpandi\SmartCut64\Signing\smartcut64-release-auth.password.dpapi'),
  [string] $MetadataFile,
  [string] $DlibPath
)

$ErrorActionPreference = 'Stop'
if (-not $MetadataFile) { $MetadataFile = Join-Path $PSScriptRoot 'artifact-signing-metadata.json' }

if (-not (Test-Path -LiteralPath $CertificatePath -PathType Leaf)) {
  throw "Artifact Signing authentication certificate was not found: $CertificatePath"
}
if (-not (Test-Path -LiteralPath $ProtectedPasswordPath -PathType Leaf)) {
  throw "Protected certificate password was not found: $ProtectedPasswordPath"
}

$savedEnvironment = @{}
$credentialVariables = @(
  'AZURE_TENANT_ID',
  'AZURE_CLIENT_ID',
  'AZURE_CLIENT_CERTIFICATE_PATH',
  'AZURE_CLIENT_CERTIFICATE_PASSWORD'
)
foreach ($name in $credentialVariables) {
  $savedEnvironment[$name] = [Environment]::GetEnvironmentVariable($name, 'Process')
}

$passwordPointer = [IntPtr]::Zero
try {
  # ConvertFrom-SecureString created this file with Windows DPAPI. It can only
  # be decrypted by the Windows account that created it, on this machine.
  $protectedPassword = (Get-Content -LiteralPath $ProtectedPasswordPath -Raw).Trim()
  if (-not $protectedPassword) { throw 'The protected certificate password file is empty' }
  $securePassword = $protectedPassword | ConvertTo-SecureString
  $passwordPointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($securePassword)
  $plainPassword = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($passwordPointer)

  $env:AZURE_TENANT_ID = $TenantId
  $env:AZURE_CLIENT_ID = $ClientId
  $env:AZURE_CLIENT_CERTIFICATE_PATH = (Resolve-Path -LiteralPath $CertificatePath).Path
  $env:AZURE_CLIENT_CERTIFICATE_PASSWORD = $plainPassword

  $arguments = @{
    BuildDir = $BuildDir
    Provider = 'ArtifactSigning'
    MetadataFile = $MetadataFile
  }
  if ($DlibPath) { $arguments.DlibPath = $DlibPath }
  & (Join-Path $PSScriptRoot 'sign-release.ps1') @arguments
} finally {
  $plainPassword = $null
  $securePassword = $null
  $protectedPassword = $null
  if ($passwordPointer -ne [IntPtr]::Zero) {
    [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($passwordPointer)
  }
  foreach ($name in $credentialVariables) {
    $savedValue = $savedEnvironment[$name]
    if ($null -eq $savedValue) {
      [Environment]::SetEnvironmentVariable($name, $null, 'Process')
    } else {
      [Environment]::SetEnvironmentVariable($name, $savedValue, 'Process')
    }
  }
}
