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

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

    [Parameter(Mandatory=$false)]
    [string]$config
)

Import-Module WebAdministration

#region configuration generators
function Write-Storage-Emulator-Configuration([string]$logDir)
{
    $registrykey="HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows Azure Storage Emulator\"
    $registrykeyvaluename="InstallPath"
    $emulatorInstallPath=Get-RegistryKeyValue -registryKey:$registrykey -registryKeyValueName:$registrykeyvaluename
    if([string]::IsNullOrEmpty($emulatorInstallPath)){
        Write-Log "Skipping Azure sdk configuration as the Azure emulator is not installed."
        break
    }

    $azurestorageemulator= join-path $emulatorInstallPath "azurestorageemulator.exe"

    $standardout=join-path $global:logdir "azurestorageemulator.stopprocess.output"
    $standarderr=join-path $global:logdir "azurestorageemulator.stopprocess.error"
    $script="`
    WindowsProcess StopEmulatorProcesses `
    { `
        Ensure=`"Absent`" `
        Arguments=`"start /inprocess`" `
        Path=`"$azurestorageemulator`" `
        DependsOn=@() `
    }"

    Write-Log "Creating the configuration to stop any storage emulator process(es)"
    Write-Content $script

    $script = @"
    DynamicsScheduledTask StartAzureStorageEmulator_ScheduledTask
    {
        TaskName = "DynamicsStartAzureStorageEmulator"
        Ensure = "Absent"
    }
"@
    Write-Content $script

}

function Write-Miscellaneous-Processes-Configuration([string]$webroot,[string]$logDir)
{
    $binarypathname=join-path $webroot "bin\Microsoft.Dynamics.AX.Deployment.Setup.exe"
    $standardoutdir=join-path $logDir "Microsoft.Dynamics.AX.Deployment.Setup.exe.output"
    $standarderrdir=join-path $logDir "Microsoft.Dynamics.AX.Deployment.Setup.exe.error"

    $script="`
    DynamicsProcess StopDeploymentSetupProcess `
    { `
        Ensure=`"Absent`" `
        Arguments=`"`" `
        File=`"$binarypathname`" `
        StandardErrorPath=`"$standardoutdir`" `
        StandardOutputPath=`"$standarderrdir`" `
        DependsOn=@(`"[WindowsProcess]StopEmulatorProcesses`") `
        MonitoringAssembly=`"$global:telemetrydll`" `
    } "

    Write-Log "Creating the configuration to stop the deployment setup process"
    Write-Content $script
}

function Write-BatchService-Configuration([string]$webroot,[string]$logDir)
{
    $webconfig= join-path $webroot "web.config"
    $binarypathname=join-path $webroot "bin\Batch.exe"
    $standardout=join-path $logDir "batch.exe.output"
    $standarderr=join-path $logDir "batch.exe.error"
    $deleteBatchServiceDependency=""
    if(Test-Path $binarypathname){
        $script="`
        WindowsProcess StopBatchProcess `
        { `
            Ensure=`"Absent`" `
            Arguments='-service $webconfig' `
            Path=`"$binarypathname`" `
        } "

        Write-Log "Creating the configuration to stop the Dynamics AX Batch process"
        Write-Content $script
        $deleteBatchServiceDependency="`"[WindowsProcess]StopBatchProcess`""
    }
    
    $servicepath=join-path $webroot "bin\Batch.exe -service $webconfig"
    $script = "`
    Service DeleteBatchService `
    { `
        Ensure=`"Absent`" `
        Name=`"DynamicsAxBatch`" `
        State=`"Stopped`" `
        DisplayName=`"Dynamics AX Batch Management`" `
        Path='$servicepath' `
        DependsOn=@($deleteBatchServiceDependency) `
    }"

    Write-Log "Creating the configuration to delete the Dynamics AX Batch service"
    Write-Content $script

    $script = @"
    DynamicsScheduledTask StartBatch_ScheduledTask
    {
        TaskName = "DynamicsStartBatch"
        Ensure = "Absent"
    }
"@
    Write-Content $script
}

function Write-WebSite-Configuration([string]$websitename,[string]$webroot,[string]$apppoolname)
{
    $source=$env:TEMP
    $script="`
    xWebSite DeleteAosWebSite `
    { `
        Ensure=`"Absent`" `
        Name=`"$websiteName`" `
        PhysicalPath=`"$webRoot`" `
        State=`"Stopped`" `
    }"

    Write-Log "Creating the configuration to delete the AOS web site"
    Write-Content $script

    if(![string]::IsNullOrEmpty($apppoolname)){
         # delete the aos apppool if it exists
        $script="`
        xWebAppPool DeleteAosAppPool `
        { `
            Ensure=`"Absent`" `
            State=`"Stopped`" `
            Name=`"$apppoolname`" `
            DependsOn=@(`"[xWebSite]DeleteAosWebSite`") `
        }"

        Write-Log "Creating the configuration to delete the AOS web app pool"
        Write-Content $script
    }

    $script= @"
    xWebAppPool DeleteProductConfigurationAppPool
    {
        Ensure="Absent"
        State="Stopped"
        Name="ProductConfiguration"
        DependsOn=@("[xWebSite]DeleteAosWebSite")
    }
"@
    Write-Log "Creating the configuration to delete the product configuration web app pool"
    Write-Content $script

    $script = "
    File DeleteWebSitePhysicalPath`
    { `
        Ensure=`"Absent`" `
        DestinationPath=`"$webRoot`" `
        Recurse=`$true `
        SourcePath=`"`" `
        Type=`"Directory`" `
        DependsOn=@(`"[xWebSite]DeleteAosWebSite`", `"[Service]DeleteBatchService`") `
        Force=`$true `
    }"

     Write-Log "Creating the configuration to delete the AOS web site files"
     Write-Content $script
    
}

function Write-Packages-Configuration([string]$packagedir)
{
    $script = "
    File DeletePackages`
    { `
        Ensure=`"Absent`" `
        DestinationPath=`"$packageDir`" `
        Recurse=`$true `
        SourcePath=`"`" `
        Type=`"Directory`" `
        Force=`$true `
        DependsOn=@(`"[xWebSite]DeleteAosWebSite`") `
    }"

    Write-Log "Creating the configuration to delete the Dynamics packages"
    Write-Content $script
}

function Write-Database-Configuration([string]$dbName,[string]$dbServer,[string]$dbUser,[string]$dbPwd,[string]$logDir)
{
    # for dropping the db, use the temp folder name as the package dir as it is not used
    $packageDir=$env:TEMP

    $script="`
    DynamicsDatabase DropDatabase `
    { `
        Ensure=`"Absent`" `
        PackageDirectory=`"$packageDir`" `
        DatabaseName=`"$dbName`" `
        DatabaseServer=`"$dbServer`" `
        UserName=`"$dbUser`" `
        Password=`"$dbPwd`" `
        DependsOn=@(`"[File]DeletePackages`") `
        MonitoringAssembly=`"$global:telemetrydll`" `
    }"

    Write-Log "Creating the configuration to drop the AX database"
    Write-Content $script
}

function Write-LCM-Configuration($thumbprint)
{
    Write-Verbose "Creating the LCM configuration to set the encryption certificate thumbprint..."
    $script="`
    LocalConfigurationManager 
    {
        CertificateId=`"$thumbprint`"
    }"
    
    write-content $script
}
#endregion

#region helper functions
function Initialize-Log([string]$logdir,[string]$logfile)
{
    if(-not (Test-Path $logdir)){
        New-Item -ItemType Directory -Path $logdir
    }
    
    if(Test-Path $logfile){
        Remove-Item $logfile -Force
    }

    New-item $logfile -ItemType File -Force
}

function Write-Log([string]$message)
{
    Add-Content $global:logfile $message
    Write-Host $message
}

function Write-Header
{
    $datetime=Get-Date
    $header="`
###
# ==++==
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# Generated date: $datetime
#
# This file is auto-generated by a tool. Any changes made to this file will be lost.
#
# This file will be compiled to generate a Windows DSC configuration that will remove 
# the Dynamics AOS service on this machine.
###

#region service configuration
Configuration RemoveAosServiceConfiguration { `
`
Import-DscResource -Module xWebAdministration `
Import-DscResource -Module xDynamics `
Import-DscResource -Module PSDesiredStateConfiguration `

Node `"localhost`"{"

    Write-Content $header
}

function Write-Footer([string]$outputpath)
{
    $footer="}`
    } `

`$configData=@{
    AllNodes=@(
        @{NodeName=`"localhost`";CertificateFile=`"$global:encryptioncertpublickeyfile`";Thumbprint=`"$global:encryptioncertthumbprint`";PSDscAllowDomainUser=`$true; }
    )
}`

#endregion

# generate the MOF file `    
RemoveAosServiceConfiguration -OutputPath:$outputpath -ConfigurationData:`$configData"

    Write-Content $footer
}

function Write-Content([string]$content)
{
   Add-Content $global:dscconfigfile -Value $content
}

function Get-RegistryKeyValue([string]$registryKey,[string]$registryKeyValueName,[string]$defaultValue=[string]::Empty)
{
    $value=(Get-ItemProperty "$registryKey").$registryKeyValueName
    if([string]::IsNullOrEmpty($value)){
        return $defaultValue
    }

    return $value
}

function Copy-CustomDSCResources([string]$grandparentDir)
{
    if(Test-Path "$grandparentDir\Scripts\xDynamics"){
        Write-Log "Copying the custom DSC resources"
        Copy-Item -Path "$grandparentDir\Scripts\xDynamics" -Destination "$env:ProgramFiles\WindowsPowerShell\Modules" -Force -Recurse -Verbose
        Get-ChildItem -Path "$env:ProgramFiles\WindowsPowerShell\Modules" -Recurse | Unblock-File -Verbose  
    }else{
        Write-Log "No custom DSC resources to copy"
    }
}

function Save-EncryptionCertificate-PublicKey($certificate)
{
    Write-Log "Saving the encryption cert public key to file..."
    $global:encryptioncertpublickeyfile=join-path $global:logdir "EncryptCert.cer"
    Export-Certificate -cert:$certificate -FilePath $global:encryptioncertpublickeyfile -Force -Type CERT | Out-Null
}

function Get-EncryptionCertificate-Thumbprint
{
    $subject="MicrosoftDynamicsAXDSCEncryptionCert"

    #get or create a new self-signed encryption certificate to secure sensitive info in the MOF files
    $cert=Get-Make-Encryption-Cert -subject:$subject
    Save-EncryptionCertificate-PublicKey -certificate:$cert
    $cert.Thumbprint
}

function Get-Make-Encryption-Cert([string]$subject)
{
    Write-Log "Checking if a self-signed encryption cert with subject '$subject' exists..."
    $formattersubject="CN=$subject"
    $cert=Get-ChildItem Cert:\LocalMachine\My|where {$_.Subject -eq $formattersubject}
    if($cert -ne $null) # if cert existed make sure it is valid
    {
        if(!(Is-ValidCert -certificate:$cert))
        {
            Write-Log "Dynamics DSC self-signed encryption cert is expired. Generating a new self-signed encryption certificate..."
            Write-Log "Deleting the invalid self-signed encryption certificate with subject '$cert.subject'... "
            $thumbprint=$cert.Thumbprint
            Remove-Item -Path Cert:\LocalMachine\My\$thumbprint -Force -DeleteKey |out-null
            $cert=Make-Certificate -subject:$subject
        }
    }
    else
    {
        $cert=Make-Certificate -subject:$subject 
    }

    $cert
}

function Is-ValidCert($certificate)
{
    $subject=$certificate.Subject
    Write-Log "Checking if the certificate '$subject' is valid..."
    $thumbprint=$certificate.Thumbprint
    $cert=Get-ChildItem -Path Cert:\LocalMachine\My\$thumbprint
    if($cert -ne $null)
    {
        if($cert.NotAfter -lt (Get-Date)) #expired
        {
            return $false
        }
        else
        {
            return $true
        }
    }

    #if cert is not found, return false
    return $false
}

function Make-Certificate([string]$subject)
{
     Write-Log "Creating a new DSC self-signed encryption certificate with subject '$subject'..."
     return New-SelfSignedCertificate -DnsName $subject -CertStoreLocation cert:\LocalMachine\My
}

function Output-CurrentEnvironmentState([string]$websitePath, [string]$packagePath)
{
    $handleExePath=join-path $env:SystemDrive "SysInternals\Handle.exe"
    $openHandlesLog=join-path $global:logDir "aosservice-uninstallation-openhandles.log"
    if(-not (Test-Path $handleExePath))
    {
        return
    }
    
    #dump any handles to files in the website directory
    if(Test-Path $websitePath)
    {
        Write-Log "AOS WebRoot still exists at $websitePath. Dumping open handles to $openHandlesLog..."
        & "$handleExePath" -AcceptEula $websitePath | Out-File $openHandlesLog -Append
    }
    
    #dump any handles to files in the package directory
    if(Test-Path $packagePath)
    {
        Write-Log "AOS packages directory still exists at $packagePath. Dumping open handles to $openHandlesLog..."
        & "$handleExePath" -AcceptEula $packagePath | Out-File $openHandlesLog -Append
    }
}

#endregion

#region Main
$parentdir=Split-Path -parent $PSCommandPath
$grandparentdir=Split-Path -parent $parentdir
$global:logfile=$log
$global:logdir=[System.IO.Path]::GetDirectoryName($log)

Initialize-Log -logdir:$global:logdir -logfile:$log
Copy-CustomDSCResources -grandparentDir:$grandparentdir

$global:decodedservicemodelxml=[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($servicemodelxml))

$global:dscconfigfile=join-path $global:logdir "Uninstall.ps1"

if(Test-Path $global:dscconfigfile){
    Remove-Item $global:dscconfigfile -Force
}

$outputpath=join-path $global:logdir "Uninstall"
$etwpath=join-path $grandparentdir "ETWManifest"
$global:telemetrydll = join-path $etwpath "Microsoft.Dynamics.AX7Deployment.Instrumentation.dll"

if(-not (Test-Path $global:telemetrydll)){
    throw "The deployment telemetry assembly does not exist"
}

[System.Xml.XmlDocument] $xd = new-object System.Xml.XmlDocument
$xd.LoadXml($global:decodedservicemodelxml)
$ns=New-Object System.Xml.XmlNamespaceManager($xd.NameTable)
$ns.AddNamespace("ns",$xd.DocumentElement.NamespaceURI)

if($env:USERDOMAIN -eq $env:COMPUTERNAME){
    $global:domain="builtin"
}else{
    $global:domain=$env:USERDOMAIN
}

$global:username=$env:USERNAME

$global:encryptioncertthumbprint=Get-EncryptionCertificate-Thumbprint

[string]$websiteName=$xd.SelectSingleNode("//ns:ServiceModel",$ns).getAttribute("Name")
[string]$webRoot=$xd.SelectSingleNode("//ns:Setting[@Name='Infrastructure.WebRoot']",$ns).getAttribute("Value")
Write-Log "The web root is $webRoot"
[string]$packageDir=$xd.SelectSingleNode("//ns:WorkingFolder[@Name='PackagesLocalDirectory']",$ns).getAttribute("Directory")
Write-Log "The package directory is $packageDir"

$website=Get-Website $websiteName
if($website -ne $null)
{
    $apppool=$website.applicationPool
}

$uninstallAttempt=1
while($uninstallAttempt -le 3 -and !$success)
{
    if($uninstallAttempt -gt 1)
    {
        $retryAttempt=$uninstallAttempt-1
        Write-Log "Retry attempt $retryAttempt`: Retrying AOS service uninstallation..."
    }

    # create the configuration file
    Write-Header 
    Write-LCM-Configuration -thumbprint:$global:encryptioncertthumbprint
    Write-Storage-Emulator-Configuration -logDir:$log
    Write-Miscellaneous-Processes-Configuration -webroot:$webroot -logDir:$log
    Write-BatchService-Configuration -webroot:$webroot -logDir:$log
    Write-WebSite-Configuration -websitename:$websiteName -webroot:$webroot -apppoolname:$apppool
    Write-Packages-Configuration -packagedir:$packageDir

    Write-Footer -outputpath:$outputpath
    #endregion

    #region execute the configuration
    Write-Log "Executing the configuration.."
    & $global:dscconfigfile
    [bool]$success=$false
    $dscConfigApplied = $false
    try
    {
        $dscConfigApplied = $false
        Set-Location $outputpath
        Write-Log ("PSModulePath is currently: "+$env:PSModulePath)

        Write-Log "Setting up LCM to decrypt credentials..."
        Set-DscLocalConfigurationManager -path "$outputpath" -Verbose *>&1 | Tee-Object $log
        
        try
        {
            Write-Log("Dumping available DSC resources before applying the configuration...")
            $availableDSCResourceLog=join-path $global:logdir "aosservice-uninstallation-availabledscresources.log"
            Get-DSCResource -Name * | Format-List | Out-File -FilePath $availableDSCResourceLog
        }
        catch
        {
            Write-Log "Failed to get DSC resources, Error: $_"
        }
        
        Write-Log "Applying the configuration..."
        Start-DscConfiguration -wait -Verbose -path "$outputpath" -Force *>&1 | Tee-Object $log
        $dscConfigApplied = $true
    }
    catch
    {
        Write-Log "Uninstall attempt $uninstallAttempt`: Error: $_"
    }

    $configstatuslog=join-path $global:logdir "aosservice-uninstallation-status.log"
    $ConfigStatus = Get-DscConfigurationStatus
    $ConfigStatus | Format-List -Property * | Out-File -FilePath $configstatuslog -Force
    if($ConfigStatus.Status -ieq 'Success' -and $dscConfigApplied -eq $true)
    {
        $success=$true
    }
    else
    {
        Output-CurrentEnvironmentState $webRoot $packageDir
        Move-Item $global:dscconfigfile (join-path $global:logdir "Uninstall_Attempt_$uninstallAttempt.ps1")
        $uninstallAttempt++
    }
}

if($success)
{
    Write-Log "Configuration applied."
    return 0
}
else
{
    throw "AOS uninstallation did not complete after 3 retries, Message: $($ConfigJob.StatusMessage), see log for details."    
}

#endregion

# SIG # Begin signature block
# MIIjkQYJKoZIhvcNAQcCoIIjgjCCI34CAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCAfYjrp8MucsvnP
# mhosShlB1xRhnlNlyhBUqLPqcZEgqKCCDYEwggX/MIID56ADAgECAhMzAAABh3IX
# chVZQMcJAAAAAAGHMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNVBAYTAlVTMRMwEQYD
# VQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNy
# b3NvZnQgQ29ycG9yYXRpb24xKDAmBgNVBAMTH01pY3Jvc29mdCBDb2RlIFNpZ25p
# bmcgUENBIDIwMTEwHhcNMjAwMzA0MTgzOTQ3WhcNMjEwMzAzMTgzOTQ3WjB0MQsw
# CQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9u
# ZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9u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