[CmdletBinding(DefaultParameterSetName = 'Windows')]
param(
    [Parameter(Mandatory, ParameterSetName = 'Windows')]
    [Parameter(Mandatory, ParameterSetName = 'Cloud Service')]
    [String]$CommonName,

    # Host for Cert Delivery, comma seperated
    [Parameter(Mandatory, ParameterSetName = 'Windows')]
    [String]$DestinationServer,

    # Option for pfx in PasswordState
    [Parameter(Mandatory, ParameterSetName = 'Windows')]
    [bool]$PfxtoPasswordState,

    # AppName CI in CMDB
    [Parameter(Mandatory, ParameterSetName = 'Cloud Service')]
    [String]$ApplicationName
)
    #PSU Reassignment per Zacks standards
    $RequestedBy = $UAJob.Identity.Name # user that started the job
    $PSUJobId = $UAJob.Id
    

$DestinationServerArray = $DestinationServer  -split ","
    if ($PSCmdlet.ParameterSetName -eq 'Windows') {
        Write-Verbose -Message "Validate host" -Verbose
        Foreach ($ComputerName in $DestinationServerArray) {
           $remotehi=Invoke-Command -ComputerName $ComputerName -ScriptBlock {"hi"} -Credential $Secret:ndgov_svcitdpsuwin
 
           if ($remotehi -eq "hi") {
             "Connection to host $ComputerName Succeded"
           } else {
             "Connection to host $ComputerName failed"
             exit
           }
        }
    }

        if ($PSCmdlet.ParameterSetName -eq 'Windows') {
            Write-Verbose -Message "Retrieve CI from ServiceNow" -Verbose 
            #We are just pulling appname from first DestinationServer
            New-ITDServiceNowSession -Environment Production -Credential $Secret:snow_vmcred
              $IP=(Resolve-DnsName -Name $DestinationServerArray[0]).IPAddress
              $Filter= "ip_address=$ip^operational_status=1"
              $Fields=("FQDN","ip_address","Location","model_id","Name","dns_domain","os_domain","Schedule","environment","sys_class_name","u_nd_application_svc","discovery_source","support_group")
              $CI= Get-ITDServiceNowRecord -Table "cmdb_ci_win_server" -Filter $Filter  -Fields $Fields -First 1
              $ApplicationName=$CI.u_nd_application_svc.display_value 
 
             if (!$ApplicationName) {
               write-Error "CI NOT FOUND"
               exit
             }
            $customFields = @(
                [pscustomobject]@{ name = "ApplicationName"; value = $ApplicationName }
            )
        }
        else  { #ParmeterSet Not Windows 
            Write-Verbose -Message "Retrieve App record from ServiceNow" -Verbose

            New-ITDServiceNowSession -Environment Production -Credential $Secret:snow_vmcred
              $Filter= "name=$ApplicationName"
              $Fields=("name")
              $CI= Get-ITDServiceNowRecord -Table "cmdb_ci_service_auto" -Filter $Filter -Fields $Fields

              if ($CI.name.value -ne $ApplicationName ) {
                    Write-Error "Could not find $ApplicationName"
                    exit
          } 
    }

    Write-Verbose -Message "Validate Email Address" -Verbose
    
    
   $RequesterEmail=Get-ICE-Snowemail -ApplicationName $ApplicationName -Credential $Secret:snow_vmcred
   $EmailAddressList = $RequesterEmail -split ","

    foreach ($e in $EmailAddressList) {
        $user = Get-ADUser -Filter "Mail -eq '$e'" -Properties Mail
        $group = Get-ADGroup -Filter "Mail -eq '$($e)'" -Properties Mail

        if ($user -or $group) {
          Write-Verbose -Message  "$e Passed testing" -Verbose
        }
         else {
                   Write-Error "$e is an invalid email address. Terminating Script"
           exit
        }
    }

   


#Set env prod

Write-Verbose -Verbose "Set DB Environment"
Set-JDEnvironment -Name prod


Write-Verbose -Verbose "Remoting to other server to get cert info"


$ComputerName=$DestinationServerArray[0]
$OldCert=Get-ICE-RemoteCertInfo -ComputerName $ComputerName -CommonName $CommonName -Credential $Secret:ndgov_svcitdpsuwin

Write-Verbose -Verbose "Old Cert"
$OldCert|fl


$ExpiryDate=$OldCert.NotAfter
$subjectAlternative = $OldCertsubjectAlternative
$ParameterSetName=$PSCmdlet.ParameterSetName
$SubjectAlternative = $OldCert.subjectAlternative
$ExpiryDate = $OldCert.NotAfter
$Thumbprint=$OldCert.Thumbprint
$PreviousThumbprint = $false



Write-Verbose -Verbose "Create Powershell object for Logging"
$log_psobject=[pscustomobject]@{
    Timestamp           = (Get-Date)
    ParameterSetName    = $ParameterSetName
    RequestedBy         = $RequestedBy
    RequesterEmail      = $RequesterEmail
    CommonName          = $CommonName
    Environment         = $CI.environment.value
    NotBefore           = $OldCert.NotBefore
    SubjectAlternative  = $SubjectAlternative
    DestinationServer   = $DestinationServer
    PfxtoPasswordState  = $PfxtoPasswordState
    ApplicationName     = $ApplicationName  
    ExpiryDate          = $ExpiryDate
    Thumbprint          = $Thumbprint  
    PreviousThumbprint  = $PreviousThumbprint
    is_retired          = $false
 } 


$bla=$log_psobject|Out-String

Write-Host $bla

#$Result = Read-Host "Does this information look correct y/n"
$Result = "y" #forcing



if ($result -eq "y") {
  Write-Verbose -Verbose "Log new transaction to both tables. "
  #Cache table common name is the primary key so there should only be an update?
   $table=@("certlog","certcache")
   Foreach ($t in $table) {
      $log_psobject| Add-JDJson -TableName $t -Verbose
   }
}
else {
"Did not Save! You are NOT Registered!"
}

Write-Verbose -Verbose "Installing Client Module"
   $InstallParams= @{
        DestinationServer         = $DestinationServer
        Email                     = $RequesterEmail
        PSUJobId                  = $PSUJobId
        Credential                = $Secret:ndgov_svcitdpsuwin
    }

Install-ICE-Client @InstallParams