---
- name: Deploy nginx virtual host config file
  ansible.builtin.template:
    src: nginx.conf.j2
    dest: "{{ cinny_nginx_available_sites }}/{{ cinny_nginx_vhost_name }}"
    mode: "0640"
  when: cinny_state == 'present'

- name: Enable nginx virtual host
  ansible.builtin.file:
    path: "{{ cinny_nginx_enabled_sites }}/{{ cinny_nginx_vhost_name }}"
    src: "{{ cinny_nginx_available_sites }}/{{ cinny_nginx_vhost_name }}"
    state: "{{ (cinny_state == 'present') | ternary('link', 'absent') }}"
  when: cinny_nginx_vhost_enable

- name: Clean up nginx virtural host config file
  ansible.builtin.file:
    path: "{{ cinny_nginx_available_sites }}/{{ cinny_nginx_vhost_name }}"
    state: absent
  when: cinny_state == 'absent'

- name: Ensure nginx configuration is valid
  ansible.builtin.command:
    cmd: "nginx -t"
  when:
    - cinny_state == 'present'
    - cinny_nginx_vhost_enable

- name: Reload nginx using systemd
  ansible.builtin.systemd_service:
    name: "nginx.service"
    state: reloaded
  when:
    - cinny_state == 'present'
    - cinny_nginx_vhost_enable
    - ansible_facts['service_mgr'] == 'systemd'

- name: Inform user about required nginx reload
  ansible.builtin.debug:
    msg: "Restart nginx service (no systemd found)"
  when:
    - cinny_state == 'present'
    - cinny_nginx_vhost_enable
    - ansible_facts['service_mgr'] != 'systemd'