---
# check nginx by listening port
- name: check nginx exists by port
  command: 'ss -tp state listening sport = :{{ nginx_port }}'
  register: check_nginx_port_result
- name: set nginx_exists flag
  connection: local
  set_fact: { nginx_exists: "{{ 'nginx' in check_nginx_port_result.stdout }}" }

# only setup repo nginx when nginx is not running
- name: setup repo nginx server
  when: not nginx_exists|bool
  block:

    # make sure nginx installed
    - name: make sure nginx installed
      environment: "{{ proxy_env | default({}) }}"
      package: name=nginx state=present

    # prepare nginx to work
    - name: nginx pre-launch adjustment
      ignore_errors: true
      shell: |
        if command -v semanage &>/dev/null; then
            setsebool -P httpd_can_network_connect on
            setsebool -P httpd_can_network_relay on
            semanage fcontext -a -t httpd_sys_content_t "{{ nginx_home }}(/.*)?" 2>/dev/null || \
            semanage fcontext -m -t httpd_sys_content_t "{{ nginx_home }}(/.*)?"
            semanage fcontext -a -t httpd_sys_content_t "{{ nginx_data }}(/.*)?" 2>/dev/null || \
            semanage fcontext -m -t httpd_sys_content_t "{{ nginx_data }}(/.*)?"
            restorecon -Rv {{ nginx_home }} {{ nginx_data }}
        fi
        if systemctl is-active firewalld &>/dev/null; then
            firewall-cmd --permanent --add-port={{ nginx_port }}/tcp
            firewall-cmd --reload
        fi
        if [[ "{{ os_package }}" == "deb" ]]; then
            if command -v ufw &>/dev/null && ufw status | grep -q "Status: active"; then
              ufw allow {{ nginx_port }}/tcp
            fi
        fi
        chown -R root:nginx "{{ nginx_data }}";
        /bin/true
      args: { executable: /bin/bash }

    # copy repo nginx config & content
    - name: render repo nginx files
      template: src={{ item.src }} dest={{ item.dest }} mode=0644
      ignore_errors: false
      with_items:
        - { src: nginx.conf.j2   ,dest: /etc/nginx/nginx.conf }
        - { src: default.conf.j2 ,dest: /etc/nginx/conf.d/default.conf }
        - { src: index.html.j2   ,dest: "{{ nginx_home }}/index.html" }

    # launch nginx with systemctl and wait for port 80 online
    - name: launch repo nginx server
      systemd: name=nginx state=restarted enabled=yes daemon_reload=yes

    - name: wait repo nginx server online
      wait_for: host=127.0.0.1 port={{ nginx_port }} state=started
...