---
- name: Join Active Directory domain
  hosts: "{{ _hosts | default(omit) }}"
  gather_facts: false

  tasks:
    - name: Extract domain controller private ip
      ansible.builtin.set_fact:
        domain_controller_private_ip: "{{ hostvars[groups['purpose_domain_controller'][0]]['private_ip_address'] }}"

    - name: Set a single address on the adapter named Ethernet
      ansible.windows.win_dns_client:
        adapter_names: 'Ethernet*'
        dns_servers: "{{ domain_controller_private_ip }}"

    - name: Ensure Demo OU exists
      run_once: true
      delegate_to: "{{ domain_controller }}"
      microsoft.ad.ou:
        name: Demo
        state: present

    - name: Update the hostname
      ansible.windows.win_hostname:
        name: "{{ inventory_hostname.split('.')[0] }}"

    - name: Join ansible.local domain
      register: r_domain_membership
      microsoft.ad.membership:
        dns_domain_name: ansible.local
        hostname: "{{ inventory_hostname.split('.')[0] }}"
        domain_admin_user: "{{ ansible_user }}@ansible.local"
        domain_admin_password: "{{ ansible_password }}"
        domain_ou_path: "OU=Demo,DC=ansible,DC=local"
        state: domain

    - name: Reboot windows machine
      when: r_domain_membership.reboot_required
      ansible.windows.win_reboot:
