---

# Reenroll IPA clients if their IPA server was reinstalled.
#
# Limited to staging hosts (because the staging IPA server was reinstalled lately) to avoid breakage
# in prod.

- name: Reenroll IPA client
  hosts: staging
  user: root

  vars_files:
  - /srv/web/infra/ansible/vars/global.yml
  - /srv/private/ansible/vars.yml
  - /srv/web/infra/ansible/vars/{{ ansible_distribution }}.yml

  tags:
    - ipa/client
    - reenroll

  tasks:

  # Preparation

  - name: Install packages
    package:
      name:
        - freeipa-client
        - krb5-workstation
      state: present

  # Checks

  - name: Check if the host can obtain a Kerberos ticket
    command: kinit -kt /etc/krb5.keytab
    ignore_errors: yes
    changed_when: no
    register: kinit_res
    when: ipa_server is defined

  - name: Ping the IPA server
    command: ipa ping
    ignore_errors: yes
    changed_when: no
    register: ipa_ping_res
    when: ipa_server is defined and kinit_res.rc == 0

  - name: Do the things, or don't
    set_fact:
      do_the_things: >-
        (
          ipa_server is defined
          and (kinit_res.rc != 0 or (ipa_ping_res.rc | default(0)) != 0)
        ) | bool

  # Do the things

  - name: Unenroll IPA client
    command: ipa-client-install --uninstall --unattended
    when: do_the_things

  - name: Apply the ipa/client role
    include_role:
      name: ipa/client
    when: do_the_things

- name: Fix ownership of directories in /home/fedora
  import_playbook: fix-home-fedora-ownerships.yml
  when: do_the_things
  tags:
    - fix-ownership
