---
- name: Install needed packages
  ansible.builtin.apt:
    name:
      - sssd-ad
      - sssd-tools
      - adcli

- name: Provide user identities from AD
  ansible.builtin.template:
    src: sssd.conf.j2
    dest: /etc/sssd/sssd.conf
    mode: '0640'
  notify: Restart sssd

- name: Check if the machine account password and the join are still valid
  ansible.builtin.shell:
    cmd: adcli testjoin -D {{ domain | upper }}
  register: adcli_test_result
  failed_when: false
  changed_when: false

  # If domjoin not valid:
- name: Join the domain
  ansible.builtin.shell:
    cmd: >
      echo "{{ ad_passwd }}" | adcli join --stdin-password -U {{ ad_user }} {{ domain | upper }}
  no_log: true
  vars:
    ad_user: "{{ 'global-admin' if (adpw.user_input | default(ansible_cmdline.adpw) | default('') | length > 0) else sssd_domjoin_user }}"
    ad_passwd: "{{ adpw.user_input | default('') if  adpw.user_input | default ('') | length > 0 else ansible_cmdline.adpw | default(sssd_domjoin_passwd) | default('') }}"
  throttle: 1
  when:
    - adpw.user_input | default('') | length > 0 or
      ansible_cmdline.adpw | default(sssd_domjoin_passwd) | default('') | length > 0
    - adcli_test_result.rc != 0
