---
- name: Fix ownership of home directories in /home/fedora
  hosts: all
  user: root

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

  tasks:
  - name: Check if /home/fedora exists
    stat:
      path: /home/fedora
      follow: yes
    register: home_fedora_res

  - name: Copy the script to the host
    copy:
      src: "{{ files }}/scripts/fix-home-fedora-ownerships.sh"
      dest: /usr/local/sbin/fix-home-fedora-ownerships.sh
      mode: 0755
    changed_when: false
    when: home_fedora_res.stat.isdir

  - name: Fix ownership of home directories in /home/fedora
    # assumes that directory name == user name
    shell:
      chdir: /home/fedora
      cmd: /usr/local/sbin/fix-home-fedora-ownerships.sh
    register: chown_res
    changed_when: "'fixing ownership:' in chown_res.stdout"
    when: home_fedora_res.stat.isdir

  - name: Delete the script from the host
    file:
      path: /usr/local/sbin/fix-home-fedora-ownerships.sh
      state: absent
    changed_when: false
    when: home_fedora_res.stat.isdir
