---
- name: Install nginx
  become: true
  ansible.builtin.dnf:
    name: nginx
    state: present

- name: Enable and start nginx
  become: true
  ansible.builtin.systemd:
    name: nginx
    state: started
    enabled: true

- name: Configure firewall for Nginx
  become: true
  ansible.posix.firewalld:
    service: "{{ item }}"
    state: enabled
    zone: internal
    permanent: true
    immediate: true
  loop:
    - http
    - https

- name: Configure SELinux for Nginx
  when: ansible_selinux.status | default("") == "enabled"
  become: true
  ansible.posix.seboolean:
    name: httpd_can_network_connect
    state: true
    persistent: true
  notify: [restart-nginx]

- name: Create certificate directory
  become: true
  ansible.builtin.file:
    path: "{{ dashboard_certificate_directory }}"
    state: directory
    owner: nginx
    group: "{{ ansible_user }}"
    mode: 0570

- name: Generate X509 private key
  become: true
  vars:
    ansible_python_interpreter: "{{ skylab_ansible_venv }}/bin/python"
  community.crypto.openssl_privatekey:
    path: "{{ dashboard_certificate_directory }}/{{ dashboard_hostname }}.key"
    type: RSA
    size: 8192
    passphrase: "{{ dashboard_certificate_password }}"
    cipher: auto
    owner: nginx
    group: "{{ ansible_user }}"
    mode: 0460

- name: Install private key password file
  become: true
  ansible.builtin.copy:
    content: "{{ dashboard_certificate_password }}"
    dest: "{{ dashboard_certificate_directory }}/{{ dashboard_hostname }}.password"
    owner: nginx
    group: "{{ ansible_user }}"
    mode: 0460

- name: Create self-signed certificate
  become: true
  vars:
    ansible_python_interpreter: "{{ skylab_ansible_venv }}/bin/python"
  community.crypto.x509_certificate:
    path: "{{ dashboard_certificate_directory }}/{{ dashboard_hostname }}.pem"
    privatekey_path: "{{ dashboard_certificate_directory }}/{{ dashboard_hostname }}.key"
    privatekey_passphrase: "{{ dashboard_certificate_password }}"
    provider: selfsigned
    owner: nginx
    group: "{{ ansible_user }}"
    mode: 0460
  notify: [restart-nginx]

- name: Copy nginx SSL parameters
  become: true
  ansible.builtin.copy:
    src: ssl-options.conf
    dest: /etc/nginx/ssl-options.conf
    owner: nginx
    group: "{{ ansible_user }}"
    mode: 0664
  notify: [restart-nginx]

- name: Export Diffie-Hellman parameters
  become: true
  ansible.builtin.command:
    cmd: openssl dhparam -out /etc/nginx/ssl-dhparam.pem 2048
    creates: /etc/nginx/ssl-dhparam.pem
  notify: [restart-nginx]

- name: Configure nginx server
  become: true
  ansible.builtin.template:
    src: nginx.conf.j2
    dest: /etc/nginx/conf.d/{{ dashboard_hostname }}.conf
    owner: nginx
    group: "{{ ansible_user }}"
    mode: 0444
  notify: [restart-nginx]
