- name: Install this role on {{ansible_os_family}}
  include: "{{ansible_os_family}}.yml"
  
# install Certbot for Nginx
- name: Install certbot
  shell: |
    snap install --classic certbot
    ln -sf /snap/bin/certbot /usr/bin/certbot
  when: nginx_certbot

- name: Configure Nginx
  copy:
    src: nginx.conf
    dest: /etc/nginx/

- name: Check system architecture
  shell: uname -m
  register: system_architecture
  
- name: Print system architecture
  debug:
    var: system_architecture.stdout

- name: Change user on ubuntu arm 
  lineinfile:
      path: /etc/nginx/nginx.conf
      regexp: "user  nginx;"
      line: "user www-data;"
  when: system_architecture.stdout == "aarch64" and ansible_os_family == "Debian"
  
- name: Create a Nginx Log symbolic link
  file:
    src: '{{item.src}}'
    dest: '{{item.dest}}'
    state: link
  with_items:
    - {src: /etc/nginx/conf.d,dest: /data/config/nginx}  
    - {src: /var/log/nginx,dest: /data/logs/nginx}

- name: Set Reverse proxy
  template:
    src: default.jinja2
    dest: /etc/nginx/conf.d/default.conf

- name: create nginx's Directory
  file:
    path: "{{item}}"
    state: directory
    recurse: true
  loop:
    - /etc/nginx/extra

- block:
  - name: Copy rewrite file
    copy:
      src: rewrite
      dest: /etc/nginx/conf.d/

  - name: Create nginx_appname.conf in /etc/nginx/conf.d/rewrite
    shell: if [ ! $( ls | grep "{{nginx_appname}}") ]; then touch {{nginx_appname}}.conf ; fi
    args:
      chdir: /etc/nginx/conf.d/rewrite
    
# add new user and password on nginx
- block: 
  - name: Insert ngnix service password authority segment
    blockinfile:
      path: /etc/nginx/conf.d/default.conf
      insertbefore: "}"
      block: |
        auth_basic "Restricted Content";
        auth_basic_user_file /etc/nginx/.htpasswd;
  - name: Init nginx password
    shell: |
      htpasswd -bc /etc/nginx/.htpasswd  {{nginx_login_account[0]}} {{nginx_login_account[1]}}
  when: nginx_login_account is defined and nginx_login_account != none
        
- name: Start Nginx
  service:
    name: nginx
    state: restarted
    enabled: yes

# display version and service state of components
- name: Get Nginx version
  shell: sudo sh -c "nginx -v 2>> /data/logs/install_version.txt"

- name: Check Nginx Service
  shell: systemctl status nginx | grep Active*
  register: check_nginx_service
  notify: check_nginx_service 
