# Copyright 2022 The Kubernetes Authors.

# 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

# http://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: Download gMSA Key Vault plugin
  win_get_url:
    url: '{{ gmsa_keyvault_url }}'
    dest: '{{ tempdir.stdout | trim }}\windows-gmsa-ccgakvplugin.zip'
  async: 1800
  poll: 60
  retries: 5
  delay: 3
  register: gmsadownload
  until: gmsadownload is not failed

- name: Unzip gMSA Key Vault Archive
  win_unzip:
    src: '{{ gmsadownload.dest }}'
    dest: '{{ kubernetes_install_path }}'
    recurse: no
    delete_archive: yes

- name: Copy gMSA Key Vault plugin to System32
  win_shell: |
    Move-Item -Force -Path {{ kubernetes_install_path }}\CCGAKVPlugin.dll -Destination {{ systemdrive.stdout | trim }}\Windows\System32\

# This is done via a script because Ansible doesn't have the ability to take ownership of registry keys
# The script enables the privilege for the process running and modifies the reg keys. Once process exits it no longer has privileges
# See https://groups.google.com/g/ansible-project/c/5Bt7jgq6ZFA/m/_XJtVzmhBwAJ
- name: Copy gMSA Key Vault installer file
  win_copy:
    src: install-gmsa-keyvault-plugin.ps1
    dest: '{{ kubernetes_install_path }}'

- name: Register gMSA Key Vault plugin
  win_shell: |
    {{ kubernetes_install_path }}\install-gmsa-keyvault-plugin.ps1

- name: Install registry CCG logging manifest
  win_shell: |
    wevtutil.exe um {{ kubernetes_install_path }}\CCGEvents.man
    wevtutil.exe im {{ kubernetes_install_path }}\CCGEvents.man

- name: Install registry Key Vault plugin logging manifest
  win_shell: |
    wevtutil.exe um {{ kubernetes_install_path }}\CCGAKVPluginEvents.man
    wevtutil.exe im {{ kubernetes_install_path }}\CCGAKVPluginEvents.man

- name: Clean up gMSA install files
  win_shell: |
    Remove-Item {{ kubernetes_install_path }}\CCGEvents.man
    Remove-Item {{ kubernetes_install_path }}\CCGAKVPluginEvents.man
    Remove-Item {{ kubernetes_install_path }}\registerplugin.reg
    Remove-Item {{ kubernetes_install_path }}\install-gmsa-keyvault-plugin.ps1