---
- name: Create Active Directory domain
  hosts: "{{ _hosts | default('os_windows') }}"
  gather_facts: false

  tasks:
    - name: Set Local Admin Password
      ansible.windows.win_user:
        name: Administrator
        password: "{{ ansible_password }}"

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

    - name: Reboot to apply new hostname
      # noqa no-handler
      when: r_rename_hostname is changed
      ansible.windows.win_reboot:
        reboot_timeout: 3600

    - name: Create new domain in a new forest on the target host
      register: r_create_domain
      microsoft.ad.domain:
        dns_domain_name: ansible.local
        safe_mode_password: "{{ lookup('community.general.random_string', min_lower=1, min_upper=1, min_special=1, min_numeric=1) }}"

    - name: Verify domain services running
      # noqa no-handler
      when: r_create_domain is changed
      ansible.builtin.include_tasks:
        file: tasks/domain_services_check.yml

    - name: Create some groups
      microsoft.ad.group:
        name: "{{ item.name }}"
        scope: global
      loop:
        - name: "GroupA"
        - name: "GroupB"
        - name: "GroupC"
      retries: 5
      delay: 10

    - name: Create some users
      microsoft.ad.user:
        name: "{{ item.name }}"
        groups: "{{ item.groups }}"
        password: "{{ lookup('community.general.random_string', min_lower=1, min_upper=1, min_special=1, min_numeric=1) }}"
        update_password: on_create
      loop:
        - name: "UserA"
          groups: "GroupA"
        - name: "UserB"
          groups: "GroupB"
        - name: "UserC"
          groups: "GroupC"
      retries: 5
      delay: 10
