---
- name: Install a global robots.txt
  when: nginx_install_robots_txt
  tags: [nginx, robots_txt]
  block:
    - name: Install a robots.txt into the global webroot
      ansible.builtin.template:
        src: robots.txt.j2
        dest: "{{ nginx_webroot }}/robots.txt"
        owner: root
        group: root
        mode: "0444"

- name: Install a virtualhost specific robots.txt
  when:
    - nginx_install_robots_txt
    - nginx_virthosts | length
    - item.root is defined
  tags: [nginx, robots_txt]
  block:
    - name: Install a robots.txt into the virtualhost webroot
      ansible.builtin.template:
        src: robots.txt.j2
        dest: "{{ item.root }}/robots.txt"
        owner: root
        group: root
        mode: "0444"
      loop: "{{ nginx_virthosts }}"
      when: nginx_webroot != item.root

- name: Remove the global robots.txt
  when: not nginx_install_robots_txt
  tags: [nginx, robots_txt]
  block:
    - name: Remove the global robots.txt
      ansible.builtin.file:
        dest: "{{ nginx_webroot }}/robots.txt"
        state: absent

- name: Remove the virtualhost specific robots.txt
  when:
    - item.root is defined
    - not nginx_install_robots_txt
    - nginx_virthosts | length
  tags: [nginx, robots_txt]
  block:
    - name: Remove the robots.txt into the virtualhost webroot
      ansible.builtin.file:
        dest: "{{ item.root }}/robots.txt"
        state: absent
      loop: "{{ nginx_virthosts }}"
