#This script is going torenew agent certificates etc
#you may need to Set-ExecutionPolicy Unrestricted

If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
 {    
	Echo "This script needs to be run as Administrator"
	Exit
 }
 
$selectedservice="DualShield"

$key = 'HKLM:\SYSTEM\CurrentControlSet\Services\' + $selectedservice
$dualservice = Get-ItemProperty -Path $key
if(!$dualservice)
{
	Write-Host "No $selectedservice service found on this machine!"
	Write-Host -NoNewLine 'Press any key to continue...';
	$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
	Exit
}

$dualimagepath = (Get-ItemProperty -Path $key).ImagePath


if($selectedservice -eq 'DualShield')
{
    $stopword = '\tomcat'
}
else
{
    $stopword = '\bin'
}

$pos = $dualimagepath.IndexOf($stopword)
#result will contain trailing backslash
if($dualimagepath[0] -eq '"')
{
    $dualpath = $dualimagepath.SubString(1,$pos)
}
else
{
    $dualpath = $dualimagepath.SubString(0,$pos+1)
}


Write-Host "Stopping DualShield Service..."
$ServiceName = $selectedservice
Stop-Service $ServiceName
# wait for 10 seconds then check status, in test- install radius, then upgrade, we saw the service was stopped, then started again!, this may improve
Start-Sleep -s 10

$arrService = Get-Service -Name $ServiceName

while($arrService.Status -ne "Stopped")
{
	Write-Host "Wait a number of seconds for the service to be stopped. if it is not done, you may need to stop it manually."
	Start-Sleep -s 10
	$arrService = Get-Service -Name $ServiceName
}

Write-Host "Renewing dualshield ultimate ca in cacerts..."
$runjava = Join-Path $dualpath "jre\bin\java.exe"
#upgrade the dualshield CA in cacerts
& $runjava -jar ca-renew-1.0-standalone.jar (Join-Path $dualpath "jre\lib\security\cacerts") JKS changeit dualultimateca changeit

$idpfull = Join-Path $dualpath "certs\idpfull.jks"

if (Test-Path $idpfull) {
    Write-Host "Renewing dualshield idp certificate..."
    #also upgrade idpfull cert
    & $runjava -jar ca-renew-1.0-standalone.jar $idpfull JKS changeit dualshieldidp changeit
    
    $filePathToTask = Join-Path $dualpath "config\appsso-metadata.xml"
    if (Test-Path $filePathToTask) {
        Write-Host "Updating the certificate in appsso-metadata.xml..."
        $keytool = Join-Path $dualpath "jre\bin\keytool.exe"
        #extract the new cert, -alias dualshieldidp, may not necessary
        $file = & $keytool -exportcert -rfc -alias dualshieldidp -keystore $idpfull -storepass changeit
        
        #Regex pattern to compare two strings
        $pattern = "BEGIN CERTIFICATE-----(.*?)-----END CERTIFICATE"

        #Perform the operation
        $result = [regex]::Match($file,$pattern).Groups[1].Value


        #Update appsso-metadata.xml
        $xml = New-Object XML
        $xml.Load($filePathToTask)
        $ns = New-Object Xml.XmlNamespaceManager $xml.NameTable
        $ns.AddNamespace("md", "urn:oasis:names:tc:SAML:2.0:metadata")
        $ns.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#")
        $element =  $xml.SelectSingleNode("/md:EntityDescriptor/md:IDPSSODescriptor/md:KeyDescriptor/ds:KeyInfo/ds:X509Data/ds:X509Certificate",$ns)
        $element.InnerText = $result
        $xml.Save($filePathToTask)
        
    }

}

Write-Host "Importing the task into dualshield..."
#import a task into 
& $runjava -jar das-task-import-1.0-standalone.jar -f (Join-Path $dualpath "tomcat\conf\server.xml")

