---
- name: Set __is_beaker_env
  set_fact:
    __is_beaker_env: "{{ lookup('env', 'BEAKERLIB') | length > 0 }}"

- name: Install ansible-freeipa
  package:
    name: ansible-freeipa
  delegate_to: 127.0.0.1
  when: __is_beaker_env

- name: Clone ansible-freeipa repo
# noqa latest[git] git-latest
  git:
    repo: https://github.com/freeipa/ansible-freeipa
    dest: /tmp/freeipa-repo
  delegate_to: 127.0.0.1
  become: false
  when: not __is_beaker_env

- name: Create role symlinks
  file:
    src: "/tmp/freeipa-repo/roles/{{ item }}/"
    dest: "{{ playbook_dir }}/roles/{{ item }}"
    state: link
  delegate_to: 127.0.0.1
  become: false
  loop:
    - ipaserver
    - ipaclient
  when: not __is_beaker_env

- name: Ensure hostname package is installed
  package:
    name: hostname
    state: present

- name: Set hostname
  hostname:
    name: ipaserver.test.local

- name: Ensure nss package is up-to-date
  package:
    name: nss
    state: latest # noqa package-latest
  when: ansible_facts.os_family == "RedHat"

- name: Run IPA server install
  vars:
    ipaserver_setup_dns: true
    ipaserver_auto_forwarders: true
    ipaadmin_password: SomeADMINpassword
    ipadm_password: SomeDMpassword
    ipaserver_domain: test.local
    ipaserver_realm: TEST.LOCAL
    ipaserver_no_dnssec_validation: true
    local_log_dir: "{{ lookup('env', 'TEST_ARTIFACTS') | d('/tmp', true) }}"
  block:
    - name: Include ipaserver role
      include_role:
        name: ipaserver
  rescue:
    - name: FAILURE - check entropy
      command: cat /proc/sys/kernel/random/entropy_avail
      changed_when: false
    - name: FAILURE - get logs for debugging
      shell: |-
        set -euo pipefail
        cd /var/log
        tar -czf /tmp/ipalogs.tgz \
          $( [[ -e messages ]] && echo messages ) \
          $( [[ -e ipaserver-install.log ]] && echo ipaserver-install.log ) \
          $( [[ -e ipaclient-install.log ]] && echo ipaclient-install.log ) \
          $( [[ -e pki ]] && echo pki )
        chmod '0644' /tmp/ipalogs.tgz
      changed_when: false
    - name: FAILURE - grab archive
      fetch:
        src: /tmp/ipalogs.tgz
        dest: "{{ local_log_dir }}/ipalogs.tgz"
        flat: true
    - name: FAILURE - unpack archive
      shell: |-
        set -euo pipefail
        cd "{{ local_log_dir }}"
        tar -xvzf ipalogs.tgz
        chmod 0644 *
      delegate_to: 127.0.0.1
      changed_when: false
    - name: Failed
      fail:
        msg: failed
