#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2021, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# template: header.j2
# This module is autogenerated using the ansible.content_builder.
# See: https://github.com/ansible-community/ansible.content_builder


DOCUMENTATION = r"""
module: vcenter_vm_guest_customization
short_description: Applies a customization specification on the virtual machine
description: Applies a customization specification on the virtual machine in {@param.name
    vm}. The actual customization happens inside the guest when the virtual machine
    is powered on. If there is a pending customization for the virtual machine and
    a new one is set, then the existing customization setting will be overwritten
    with the new settings.
options:
    configuration_spec:
        description:
        - Settings to be applied to the guest during the customization. This parameter
            is mandatory.
        - 'Valid attributes are:'
        - ' - C(windows_config) (dict): Guest customization specification for a Windows
            guest operating system'
        - If unset, ConfigurationSpec.linux-config or ConfigurationSpec.cloud-config
            must be set. Otherwise, an appropriate fault will be thrown. (['set'])
        - '   - Accepted keys:'
        - '     - reboot (string): This option specifies what should be done to the
            guest after the customization.'
        - 'Accepted value for this field:'
        - '       - C(NO_REBOOT)'
        - '       - C(REBOOT)'
        - '       - C(SHUTDOWN)'
        - '     - sysprep (object): Customization settings like user details, administrator
            details, etc for the windows guest operating system. Exactly one of WindowsConfiguration.sysprep
            or WindowsConfiguration.sysprep-xml must be specified.'
        - If unset, sysprep settings will not be applied to the windows guest operating
            system.
        - '     - sysprep_xml (string): All settings specified in a XML format. This
            is the content of a typical answer.xml file that is used by System administrators
            during the Windows image customization. Check https://docs.microsoft.com/en-us/windows-hardware/manufacture/desktop/update-windows-settings-and-scripts-create-your-own-answer-file-sxs
            Exactly one of WindowsConfiguration.sysprep or WindowsConfiguration.sysprep-xml
            must be specified.'
        - If unset, sysprep settings will not be applied to the windows guest operating
            system.
        - ' - C(linux_config) (dict): Guest customization specification for a linux
            guest operating system'
        - If unset, ConfigurationSpec.windows-config or ConfigurationSpec.cloud-config
            must be set. Otherwise, an appropriate fault will be thrown. (['set'])
        - '   - Accepted keys:'
        - '     - hostname (object): The computer name of the (Windows) virtual machine.
            A computer name may contain letters (A-Z), numbers(0-9) and hyphens (-)
            but no spaces or periods (.). The name may not consist entirely of digits.
            A computer name is restricted to 15 characters in length. If the computer
            name is longer than 15 characters, it will be truncated to 15 characters.
            Check HostnameGenerator for various options.'
        - '     - domain (string): The fully qualified domain name.'
        - '     - time_zone (string): The case-sensitive time zone, such as Europe/Sofia.
            Valid time zone values are based on the tz (time zone) database used by
            Linux. The values are strings (string) in the form "Area/Location," in
            which Area is a continent or ocean name, and Location is the city, island,
            or other regional designation. '
        - ' See the https://kb.vmware.com/kb/2145518 for a list of supported time
            zones for different versions in Linux.'
        - ''
        - If unset, time zone is not modified inside guest operating system.
        - '     - script_text (string): The script to run before and after Linux guest
            customization.'
        - ' The max size of the script is 65536 bytes. As long as the script (shell,
            perl, python...) has the right "#!" in the header, it is supported. The
            caller should not assume any environment variables when the script is
            run. '
        - ' The script is invoked by the customization engine using the command line:
            1) with argument "precustomization" before customization, 2) with argument
            "postcustomization" after customization. The script should parse this
            argument and implement pre-customization or post-customization task code
            details in the corresponding block. '
        - ''
        - ' A Linux shell script example: '
        - ''
        - '  #!/bin/sh'
        - ' if [ x$1 == x"precustomization" ]; then'
        - ' echo "Do Precustomization tasks"'
        - ' #code for pre-customization actions...'
        - ' elif [ x$1 == x"postcustomization" ]; then'
        - ' echo "Do Postcustomization tasks"'
        - ' #code for post-customization actions...'
        - ' fi'
        - ' '
        - ''
        - If unset, no script will be executed.
        - ' - C(cloud_config) (dict): Guest customization specification with cloud
            configuration.'
        - If unset, ConfigurationSpec.windows-config or ConfigurationSpec.linux-config
            must be set. Otherwise, an appropriate fault will be thrown. (['set'])
        - '   - Accepted keys:'
        - '     - type (string): This option specifies different types of the cloud
            configuration.'
        - 'Accepted value for this field:'
        - '       - C(CLOUDINIT)'
        - '     - cloudinit (object): cloud-init configuration'
        - This field is optional and it is only relevant when the value of CloudConfiguration.type
            is CLOUDINIT.
        required: true
        type: dict
    global_DNS_settings:
        description:
        - Global DNS settings constitute the DNS settings that are not specific to
            a particular virtual network adapter. This parameter is mandatory.
        - 'Valid attributes are:'
        - ' - C(dns_suffix_list) (list): List of name resolution suffixes for the
            virtual network adapter. This list applies to both Windows and Linux guest
            customization. For Linux, this setting is global, whereas in Windows,
            this setting is listed on a per-adapter basis.'
        - If unset, no DNS suffixes are set. (['set'])
        - ' - C(dns_servers) (list): List of DNS servers, for a virtual network adapter
            with a static IP address. If this list is empty, then the guest operating
            system is expected to use a DHCP server to get its DNS server settings.
            These settings configure the virtual machine to use the specified DNS
            servers. These DNS server settings are listed in the order of preference.'
        - If unset, no DNS servers are set. (['set'])
        required: true
        type: dict
    interfaces:
        description:
        - IP settings that are specific to a particular virtual network adapter. The
            AdapterMapping structure maps a network adapter's MAC address to its IPSettings.
            May be empty if there are no network adapters, else should match number
            of network adapters configured for the VM. This parameter is mandatory.
        - 'Valid attributes are:'
        - ' - C(mac_address) (str): The MAC address of a network adapter being customized. '
        - ' In vSphere 7.0 series, the MAC addresses must be specified in the ascending
            order of pciSlotNumber, otherwise a MAC address mismatch error will be
            reported. For further details, see the https://kb.vmware.com/s/article/87648 '
        - ''
        - ''
        - ''
        - If unset, the customization process maps the the settings from the list
            of I(i_p_settings) in the CustomizationSpec.interfaces to the virtual
            machine's network adapters, in PCI slot order. The first virtual network
            adapter on the PCI bus is assigned interfaces[0].IPSettings, the second
            adapter is assigned interfaces[1].IPSettings, and so on. (['set'])
        - ' - C(adapter) (dict): The IP settings for the associated virtual network
            adapter. ([''set''])'
        - '   This key is required with [''set''].'
        - '   - Accepted keys:'
        - '     - ipv4 (object): Specification to configure IPv4 address, subnet mask
            and gateway info for this virtual network adapter.'
        - If unset, no IPv4 addresses are set.
        - '     - ipv6 (object): Specification to configure IPv6 address, subnet mask
            and gateway info for this virtual network adapter.'
        - If unset, no IPv6 addresses are set.
        - '     - windows (object): Windows settings to be configured for this specific
            virtual Network adapter. This is valid only for Windows guest operating
            systems.'
        - If unset, no specific Windows settings are set.
        elements: dict
        required: true
        type: list
    session_timeout:
        description:
        - 'Timeout settings for client session. '
        - 'The maximal number of seconds for the whole operation including connection
            establishment, request sending and response. '
        - The default value is 300s.
        type: float
        version_added: 2.1.0
    state:
        choices:
        - set
        default: set
        description: []
        type: str
    vcenter_hostname:
        description:
        - The hostname or IP address of the vSphere vCenter
        - If the value is not specified in the task, the value of environment variable
            C(VMWARE_HOST) will be used instead.
        required: true
        type: str
    vcenter_password:
        description:
        - The vSphere vCenter password
        - If the value is not specified in the task, the value of environment variable
            C(VMWARE_PASSWORD) will be used instead.
        required: true
        type: str
    vcenter_rest_log_file:
        description:
        - 'You can use this optional parameter to set the location of a log file. '
        - 'This file will be used to record the HTTP REST interaction. '
        - 'The file will be stored on the host that runs the module. '
        - 'If the value is not specified in the task, the value of '
        - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
        type: str
    vcenter_username:
        description:
        - The vSphere vCenter username
        - If the value is not specified in the task, the value of environment variable
            C(VMWARE_USER) will be used instead.
        required: true
        type: str
    vcenter_validate_certs:
        default: true
        description:
        - Allows connection when SSL certificates are not valid. Set to C(false) when
            certificates are not trusted.
        - If the value is not specified in the task, the value of environment variable
            C(VMWARE_VALIDATE_CERTS) will be used instead.
        type: bool
    vm:
        description:
        - The unique identifier of the virtual machine that needs to be customized.
        - The parameter must be the id of a resource returned by M(vmware.vmware_rest.vcenter_vm_info).
            This parameter is mandatory.
        required: true
        type: str
author:
- Ansible Cloud Team (@ansible-collections)
version_added: 0.1.0
requirements:
- vSphere 7.0.3 or greater
- python >= 3.6
- aiohttp
notes:
- Tested on vSphere 7.0.3
"""

EXAMPLES = r"""
##########
#
# VM customization can be difficult to troubleshoot, since each environment is different. Here are some general tips:
#
# 1. Make sure perl is installed on the Linux systems. Make sure cloud-init is installed if using cloud-init
# 2. Custom script execution is disabled by default. To enable it, you can run as root: vmware-toolbox-cmd config set deployPkg enable-custom-scripts  true
# 3. VMware tools must be installed and recognized by vCenter before you can apply customization. See the example below for one approach to this.
# 4. On Linux (RHEL specifically), customization script logs can be found at /var/log/vmware-imc/toolsDeployPkg.log
# 5. Once the VM is started, the pending customization is applied. Even if that fails, the customization is then cleared. Meaning, you need to re-apply
#    the customization spec in order to try again. Simply rebooting the VM will not change anything.
#
##########

#
# Here is the basic workflow for creating a new VM and then customizing it
#
- name: Deploy a new VM based on a template
  vmware.vmware_rest.vcenter_vmtemplate_libraryitems:
    name: vm-from-template
    library: "{{ library_id }}"
    template_library_item: "{{ template_id }}"
    placement:
      cluster: "{{ lookup('vmware.vmware_rest.cluster_moid', '/my_dc/host/my_cluster') }}"
    state: deploy
  register: my_new_vm

# If your template already has vmtools installed and vCenter recognizes the installation (you should be able to see the tools version when the template
# is cloned), then you can skip this block in your workflow.
- name: Register VMware Tools with vCenter
  block:
    - name: Power on the VM
      vmware.vmware_rest.vcenter_vm_power:
        state: start
        vm: "{{ my_new_vm.id }}"
    - name: Wait until my VMware tools are recognized
      vmware.vmware_rest.vcenter_vm_tools_info:
        vm: "{{ my_new_vm.id }}"
      register: vm_tools_info
      until:
        - vm_tools_info is not failed
        - vm_tools_info.value.run_state == "RUNNING"
      retries: 60
      delay: 5
    - name: Power Off VM
      vmware.vmware_rest.vcenter_vm_power:
        state: stop
        vm: "{{ my_new_vm.id }}"

- name: Customize the VM
  vmware.vmware_rest.vcenter_vm_guest_customization:
    vm: "{{ my_new_vm.id }}"
    global_DNS_settings:
      dns_suffix_list:
        - lan
        - foo.internal
      dns_servers:
        - "8.8.8.8"
    interfaces:
      - adapter:
          ipv4:
            type: DHCP
    configuration_spec:
      linux_config:
        domain: test
        hostname:
          fixed_name: myhost
          type: FIXED

- name: Power on the VM
  vmware.vmware_rest.vcenter_vm_power:
    state: start
    vm: "{{ my_new_vm.id }}"

#
# Here is an example using the Linux script text. The script shebang can be anything (bash, perl, python), so long as the script will actually run
# There is also size and length limitation on the script text, as described in the module documentation.
# Finally, note the script is run twice. Once before all of the other customization and once after.
#
- name: Customize the VM
  vmware.vmware_rest.vcenter_vm_guest_customization:
    vm: "{{ my_new_vm.id }}"
    global_DNS_settings:
      dns_suffix_list:
        - lan
        - foo.internal
      dns_servers:
        - "8.8.8.8"
    interfaces:
      - adapter:
          ipv4:
            type: DHCP
    configuration_spec:
      linux_config:
        domain: test
        hostname:
          fixed_name: myhost
          type: FIXED
        script_text: |
          #!/bin/sh
          if [ x$1 == x"precustomization" ]; then
            echo "PRE" >> /tmp/vmware_rest_init_script.log
            # add any other pre-customization tasks here
          fi

          if [ x$1 == x"postcustomization" ]; then
            echo "POST" >> /tmp/vmware_rest_init_script.log
            # add any other post-customization tasks here
          fi

#
# Here is a simple example using cloud-init
# See also:
#   https://developer.broadcom.com/xapis/vsphere-automation-api/latest/vcenter/data-structures/Guest_CloudinitConfiguration/
#   https://knowledge.broadcom.com/external/article/311895/how-to-customize-virtual-machine-using-c.html
#   https://cloudinit.readthedocs.io/en/latest/reference/examples.html
#   https://cloudinit.readthedocs.io/en/23.4.1/reference/datasources/vmware.html#walkthrough-of-guestinfo-keys-transport
#
#   cloud-init required: metadata as plain-text JSON/YAML, maximum 512KB file size
#   cloud-init optional: userdata as plain-text in raw cloud-init format with no compression / no base64 encoding, maximum 512KB file size
#
- name: Customize the VM
  vmware.vmware_rest.vcenter_vm_guest_customization:
    vm: "{{ my_new_vm.id }}"
    global_DNS_settings:
      dns_suffix_list: []
      dns_servers:
        - "8.8.8.8"
    interfaces:
      - adapter:
          ipv4:
            type: DHCP
    configuration_spec:
      cloud_config:
        type: CLOUDINIT
        cloudinit:
          metadata: |
            instance-id: cloud-vm-example-1
            local-hostname: cloud-vm
            network:
              config: disabled
          userdata: |
            #cloud-config
            disable_root: 0
            write_files:
              - content: |
                  This is a test
                path: /root/cloud-init-example

#
# Here is a more complex cloud-init example
#
- name: Set cloud-init variables for customization specification
  ansible.builtin.set_fact:
    metadata_yaml:
      instance-id: "{{ vm_name }}"
      hostname: "{{ vm_name }}"
      local-hostname: "{{ vm_name }}"
      network:
        version: 2
        ethernets:
          nics:
            match:
              name: e*
            dhcp4: true
            dhcp6: false
      public_ssh_keys:
        - "{{ lookup('ansible.builtin.file', vmware_vm_ssh_public_key_file_path) }}"

    userdata_yaml_text: |
      #cloud-config
      hostname: {{ vm_name }}
      fqdn: {{ vm_name }}.{{ vm_domain }}

      disable_root: false
      ssh_pwauth: false
      ssh_deletekeys: true
      ssh:
        emit_keys_to_console: false
      no_ssh_fingerprints: false
      ssh_authorized_keys:
        - {{ lookup('ansible.builtin.file', vmware_vm_ssh_public_key_file_path) }}

      users:
        - name: root
          ssh_authorized_keys:
            - {{ lookup('ansible.builtin.file', vmware_vm_ssh_public_key_file_path) }}
          lock_passwd: false

      write_files:
        - path: /etc/cloud/cloud-init.disabled
          permissions: "0644"
          content: ""

- name: Apply customization specification to the VM in Powered Off state
  vmware.vmware_rest.vcenter_vm_guest_customization:
    vm: "{{ my_new_vm.id }}"
    configuration_spec:
      cloud_config:
        type: CLOUDINIT
        cloudinit:
          metadata: "{{ metadata_yaml | to_json(ensure_ascii=true) }}"
          userdata: "{{ userdata_yaml_text | trim }}" # remove last newline character
    interfaces: []
    global_DNS_settings: {}
"""

RETURN = r"""
# content generated by the update_return_section callback# task: Customize the VM
value:
  description: Customize the VM
  returned: On success
  sample: {}
  type: dict
"""


# This structure describes the format of the data expected by the end-points
PAYLOAD_FORMAT = {
    "set": {
        "query": {},
        "body": {
            "configuration_spec": "spec/configuration_spec",
            "global_DNS_settings": "spec/global_DNS_settings",
            "interfaces": "spec/interfaces",
        },
        "path": {"vm": "vm"},
    }
}  # pylint: disable=line-too-long

from ansible.module_utils.basic import env_fallback

try:
    from ansible_collections.cloud.common.plugins.module_utils.turbo.exceptions import (
        EmbeddedModuleFailure,
    )
    from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
        AnsibleTurboModule as AnsibleModule,
    )

    AnsibleModule.collection_name = "vmware.vmware_rest"
except ImportError:
    from ansible.module_utils.basic import AnsibleModule
from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
    exists,
    gen_args,
    get_subdevice_type,
    open_session,
    prepare_payload,
    session_timeout,
    update_changed_flag,
)


def prepare_argument_spec():
    argument_spec = {
        "vcenter_hostname": dict(
            type="str",
            required=True,
            fallback=(env_fallback, ["VMWARE_HOST"]),
        ),
        "vcenter_username": dict(
            type="str",
            required=True,
            fallback=(env_fallback, ["VMWARE_USER"]),
        ),
        "vcenter_password": dict(
            type="str",
            required=True,
            no_log=True,
            fallback=(env_fallback, ["VMWARE_PASSWORD"]),
        ),
        "vcenter_validate_certs": dict(
            type="bool",
            required=False,
            default=True,
            fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
        ),
        "vcenter_rest_log_file": dict(
            type="str",
            required=False,
            fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
        ),
        "session_timeout": dict(
            type="float",
            required=False,
            fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
        ),
    }

    argument_spec["configuration_spec"] = {"required": True, "type": "dict"}
    argument_spec["global_DNS_settings"] = {"required": True, "type": "dict"}
    argument_spec["interfaces"] = {"required": True, "type": "list", "elements": "dict"}
    argument_spec["state"] = {"type": "str", "choices": ["set"], "default": "set"}
    argument_spec["vm"] = {"required": True, "type": "str"}

    return argument_spec


async def main():
    required_if = list([])

    module_args = prepare_argument_spec()
    module = AnsibleModule(
        argument_spec=module_args, required_if=required_if, supports_check_mode=True
    )
    if not module.params["vcenter_hostname"]:
        module.fail_json("vcenter_hostname cannot be empty")
    if not module.params["vcenter_username"]:
        module.fail_json("vcenter_username cannot be empty")
    if not module.params["vcenter_password"]:
        module.fail_json("vcenter_password cannot be empty")
    try:
        session = await open_session(
            vcenter_hostname=module.params["vcenter_hostname"],
            vcenter_username=module.params["vcenter_username"],
            vcenter_password=module.params["vcenter_password"],
            validate_certs=module.params["vcenter_validate_certs"],
            log_file=module.params["vcenter_rest_log_file"],
        )
    except EmbeddedModuleFailure as err:
        module.fail_json(err.get_message())
    result = await entry_point(module, session)
    module.exit_json(**result)


# template: default_module.j2
def build_url(params):
    return (
        "https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/guest/customization"
    ).format(**params)


async def entry_point(module, session):

    if module.params["state"] == "present":
        if "_create" in globals():
            operation = "create"
        else:
            operation = "update"
    elif module.params["state"] == "absent":
        operation = "delete"
    else:
        operation = module.params["state"]

    func = globals()["_" + operation]

    return await func(module.params, session)


async def _set(params, session):
    _in_query_parameters = PAYLOAD_FORMAT["set"]["query"].keys()
    payload = prepare_payload(params, PAYLOAD_FORMAT["set"])
    subdevice_type = get_subdevice_type("/api/vcenter/vm/{vm}/guest/customization")
    if subdevice_type and not params[subdevice_type]:
        _json = await exists(params, session, build_url(params))
        if _json:
            params[subdevice_type] = _json["id"]
    _url = (
        "https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/guest/customization"
    ).format(**params) + gen_args(params, _in_query_parameters)
    async with session.get(_url, json=payload, **session_timeout(params)) as resp:
        before = await resp.json()

    async with session.put(_url, json=payload, **session_timeout(params)) as resp:
        try:
            if resp.headers["Content-Type"] == "application/json":
                _json = await resp.json()
        except KeyError:
            _json = {}
        if "value" not in _json:  # 7.0.2
            _json = {"value": _json}

        # The PUT answer does not let us know if the resource has actually been
        # modified
        if resp.status < 300:
            async with session.get(
                _url, json=payload, **session_timeout(params)
            ) as resp_get:
                after = await resp_get.json()
                if before == after:
                    return await update_changed_flag(after, resp_get.status, "get")
        return await update_changed_flag(_json, resp.status, "set")


if __name__ == "__main__":
    import asyncio

    current_loop = asyncio.new_event_loop()
    try:
        asyncio.set_event_loop(current_loop)
        current_loop.run_until_complete(main())
    finally:
        current_loop.close()
