---
- set_fact:
    ping_user: copr-ping
    ping_homedir: /home/copr-ping
    ping_log: /var/log/copr-ping.log
    ping_script: copr-ping-script.sh
  tags: copr_ping

- stat: path={{ ping_log }}
  register: ping_log_check
  tags: copr_ping

- name: create the user ping user
  user: name={{ ping_user }}
  tags: copr_ping

- name: pre-create ping log file
  file:
    path: "{{ ping_log }}"
    owner: "{{ ping_user }}"
    group: nagios
    mode: '0644'
    state: touch
  register: ping_log_created
  when: not ping_log_check.stat.exists
  tags: copr_ping

- name: install copr-cli package
  dnf: name=copr-cli state=latest
  tags: copr_ping

- name: install the ping script
  template:
    dest: "{{ ping_homedir }}/{{ ping_script }}"
    src: "{{ ping_script }}.j2"
    owner: "{{ ping_user }}"
    group: "{{ ping_user }}"
    mode: 0700
  tags: copr_ping

- name: install the check script
  template:
    dest: "/usr/bin/copr-ping-check.py"
    src: "copr-ping-check.py.j2"
    owner: "{{ ping_user }}"
    group: "nagios"
    mode: 0750
  tags: copr_ping

- name: selinux - allow nrpe_t to read ping_log
  sefcontext:
    target: "{{ ping_log }}"
    setype: nrpe_var_run_t
    state: present
  register: semanage_run
  tags: copr_ping

- name: restorecon ping_log
  shell: restorecon -irv "{{ ping_log }}"
  when: semanage_run.changed or ping_log_created.changed
  tags: copr_ping

- name: create home/.config dir
  file:
    path: "{{ ping_homedir }}/.config"
    owner: "{{ ping_user }}"
    group: "{{ ping_user }}"
    mode: 0755
    state: directory
  tags: copr_ping

- name: install the Copr API token
  copy:
    content: |
      [copr-cli]
      login = {{ copr_ping_bot_login }}
      username = bot-copr-ping
      token = {{ copr_ping_bot_token }}
      copr_url = https://copr.fedorainfracloud.org
    dest: "{{ ping_homedir }}/.config/copr"
    mode: 0600
    owner: "{{ ping_user }}"
    group: "{{ ping_user }}"
  tags: copr_ping
  when: not devel

- name: rebuild the copr-ping package periodically
  ansible.builtin.cron:
    # NOTE: sync with CRON_PERIOD in roles/copr/backend/templates/copr-ping-check.py.j2
    name: build the ping package
    minute: "0,30"
    hour: "*"
    user: copr-ping
    job: "{{ ping_homedir }}/{{ ping_script }}"
  tags: copr_ping
