# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

- name: Create server certificate
  ansible.windows.win_powershell:
    script: |
      $Certificate = Get-ChildItem -Path Cert:\LocalMachine\My | Where-Object {$_.Subject -eq "CN={{ adfs_dns_domain_name }}"}
      if(-not $Certificate) {
        $Certificate = New-SelfSignedCertificate `
          -Subject {{ adfs_dns_domain_name }} `
          -KeyAlgorithm RSA `
          -KeyLength 2048 `
          -KeyExportPolicy NonExportable `
          -KeyUsage DigitalSignature, KeyEncipherment `
          -Provider 'Microsoft Platform Crypto Provider' `
          -NotAfter (Get-Date).AddDays(365) `
          -Type SSLServerAuthentication `
          -CertStoreLocation 'Cert:\LocalMachine\My' `
          -DnsName {{ adfs_dns_domain_name }}
      }
      $Certificate.Thumbprint
  register: server_cert

- name: Create token signing certificate
  ansible.windows.win_powershell:
    script: |
      $Certificate = Get-ChildItem -Path Cert:\LocalMachine\My | Where-Object {$_.Subject -eq "CN=ADFS Signing"}
      if(-not $Certificate) {
        $Certificate = New-SelfSignedCertificate `
          -Subject "ADFS Signing" `
          -KeyAlgorithm RSA `
          -KeyLength 2048 `
          -KeyExportPolicy NonExportable `
          -KeyUsage DigitalSignature, KeyEncipherment `
          -Provider 'Microsoft RSA SChannel Cryptographic Provider' `
          -NotAfter (Get-Date).AddDays(365) `
          -DnsName {{ adfs_dns_domain_name }} `
          -CertStoreLocation 'Cert:\LocalMachine\My'
      }
      $Certificate.Thumbprint
  register: token_signing_cert

- name: Create AD FS DKM container
  ansible.windows.win_powershell:
    script: |
      $DkmContainer = Get-ADObject -LDAPFilter "(Objectclass=container)" -SearchBase "CN=ADFS Data,{{ cloud_path }}" -SearchScope 1
      if(-not $DkmContainer) {
        $DkmContainer.DistinguishedName   
        $Name = (New-Guid).Guid
        $DkmContainer = New-ADObject `
          -Name $Name `
          -Type Container `
          -Path "CN=ADFS Data,{{ cloud_path }}" `
          -PassThru
      }
      $DkmContainer.DistinguishedName
  register: adfs_dkm_container  

- name: Install ADFS
  ansible.windows.win_powershell:
    script: |
      try {
        $AdfsFarm = Get-AdfsFarmInformation        
      } catch [System.ServiceModel.EndpointNotFoundException] {
        $AdfsCredential = New-Object `
          -TypeName System.Management.Automation.PSCredential `
          -ArgumentList "$env:userdomain\adfssvc", (ConvertTo-SecureString {{ adfssvc_password }} -AsPlainText -Force)
        Install-ADFSFarm `
          -CertificateThumbprint {{ server_cert.output[0] }} `
          -SigningCertificateThumbprint {{ token_signing_cert.output[0] }} `
          -DecryptionCertificateThumbprint {{ token_signing_cert.output[0] }}`
          -FederationServiceName {{ adfs_dns_domain_name }} `
          -ServiceAccountCredential $AdfsCredential `
          -OverwriteConfiguration `
          -AdminConfiguration @{"DKMContainerDn"="{{ adfs_dkm_container.output[0] }}"}
      }
  no_log: yes

- name: Configure TLS
  ansible.windows.win_powershell:
    script: |
      netsh http show sslcert ipport=0.0.0.0:443
      if($LastExitCode -gt 0) {
        netsh http add sslcert ipport=0.0.0.0:443 certhash={{ server_cert.output[0] }} appid="{5d89a20c-beab-4389-9447-324788eb944a}" certstorename=MY
      }

- name: Restart computer
  ansible.windows.win_reboot:

- name: Enable the Idp-Initiated Sign on page
  ansible.windows.win_powershell:
    script: |
      Set-AdfsProperties -EnableIdpInitiatedSignonPage $true