---
- name: Configure Nginx with htpasswd authentication and HTTPS via Certbot
  hosts: all
  become: yes

  tasks:
    - name: Update package list
      apt:
        update_cache: yes

    - name: Upgrade all packages
      apt:
        upgrade: dist

    - name: Install Nginx
      apt:
        name: nginx
        state: present
        update_cache: yes

    - name: Start and enable Nginx
      service:
        name: nginx
        state: started
        enabled: yes

    - name: Create directory for website
      file:
        path: "/var/www/{{ domain_name }}"
        state: directory
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        mode: '0755'

#    - name: Create a simple homepage
#      copy:
#        content: |
#          <html>
#          <head><title>Welcome to {{ domain_name }}</title></head>
#          <body><h1>Welcome to {{ domain_name }}</h1></body>
#          </html>
#        dest: "/var/www/{{ domain_name }}/index.html"
#        owner: www-data
#        group: www-data
#        mode: '0644'

    - name: Install apache2-utils package for htpasswd
      apt:
        name: apache2-utils
        state: present
        update_cache: yes

    - name: Create htpasswd file with first user
      command: >
        htpasswd -bc {{ htpasswd_file }} {{ users[0].username }} {{ users[0].password }}
      args:
        creates: "{{ htpasswd_file }}"  # Don't recreate file if it already exists

    - name: Add subsequent users to htpasswd file
      command: >
        htpasswd -b {{ htpasswd_file }} {{ item.username }} {{ item.password }}
      loop: "{{ users[1:] }}"  # Skip first user already added
      when: users | length > 1  # Execute only if there is more than one user

    - name: Configure Nginx site with authentication (HTTP)
      template:
        src: nginx_site_http.conf.j2
        dest: "/etc/nginx/sites-available/{{ domain_name }}"
        owner: root
        group: root
        mode: '0644'

    - name: Enable Nginx site
      file:
        src: "/etc/nginx/sites-available/{{ domain_name }}"
        dest: "/etc/nginx/sites-enabled/{{ domain_name }}"
        state: link

    - name: Test Nginx configuration
      command: nginx -t
      register: nginx_test
      changed_when: false
      notify: Restart Nginx

    - name: Restart Nginx to apply changes
      service:
        name: nginx
        state: restarted

    - name: Install Certbot and Nginx plugin
      apt:
        name:
          - certbot
          - python3-certbot-nginx
        state: present
        update_cache: yes

    - name: Obtain SSL certificate with Certbot
      command: >
        certbot --nginx -d {{ domain_name }} --non-interactive --agree-tos --email {{ email }} --redirect
      notify: Restart Nginx

  handlers:
    - name: Restart Nginx
      service:
        name: nginx
        state: restarted
