param(
    [Parameter(Mandatory = $true)]
    [string]$Plink,

    [Parameter(Mandatory = $true)]
    [string]$Pscp,

    [Parameter(Mandatory = $true)]
    [string]$UserHost,

    [Parameter(Mandatory = $true)]
    [string]$Password,

    [Parameter(Mandatory = $true)]
    [string]$PfxSource,

    [Parameter(Mandatory = $true)]
    [string]$RemotePfxDst,

    [Parameter(Mandatory = $true)]
    [string]$PfxPassword
)

. "$PSScriptRoot\base.legacy"

# 统一转成 Windows 风格路径，方便远程 PowerShell / certutil 使用
$remotePfxWin = $RemotePfxDst -replace '/', '\'

# 远程临时导出的 cer 路径
$remoteCerWin = [System.IO.Path]::ChangeExtension($remotePfxWin, ".cer")

# 1) 上传 pfx 到远程
$ret = Invoke-RemoteCopy $PfxSource "${UserHost}:/${RemotePfxDst}"
if ($ret -ne 0) {
    Write-Host "upload pfx failed: $ret"
    exit $ret
}

# 2) 导入 PFX 到 LocalMachine\My
# 3) 导出公钥证书到 cer
# 4) 导入到 Root 和 TrustedPublisher
# 5) 删除临时 cer
$ps = @"
`$ErrorActionPreference = 'Stop'

`$pfxPath = '$remotePfxWin'
`$cerPath = '$remoteCerWin'
`$pwd = ConvertTo-SecureString '$PfxPassword' -AsPlainText -Force

`$cert = Import-PfxCertificate `
    -FilePath `$pfxPath `
    -CertStoreLocation 'Cert:\LocalMachine\My' `
    -Password `$pwd `
    -Exportable

if (`$null -eq `$cert) {
    throw 'Import-PfxCertificate failed'
}

Export-Certificate `
    -Cert `$cert `
    -FilePath `$cerPath `
    -Force | Out-Null

Import-Certificate `
    -FilePath `$cerPath `
    -CertStoreLocation 'Cert:\LocalMachine\Root' | Out-Null

Import-Certificate `
    -FilePath `$cerPath `
    -CertStoreLocation 'Cert:\LocalMachine\TrustedPublisher' | Out-Null

Remove-Item `$cerPath -Force -ErrorAction SilentlyContinue

Write-Host 'certificate imported successfully'
"@

# 压成单行，避免多行命令通过 ssh 时不好传
$psOneLine = $ps -replace "`r", "" -replace "`n", "; "

$ret = Invoke-RemoteCmd "powershell -NoProfile -ExecutionPolicy Bypass -Command `"$psOneLine`""

Write-Host "exit code: $ret"
exit $ret

