---
- name: perform optional versionscheck
  ansible.builtin.include_tasks: versioncheck.yml
  when: submodules_versioncheck|bool

- name: Gather variables for each operating system
  include_vars: "{{ item }}"
  with_first_found:
    - "{{ ansible_distribution | lower }}-{{ ansible_distribution_version | lower }}.yml"
    - "{{ ansible_distribution | lower }}-{{ ansible_distribution_major_version | lower }}.yml"
    - "{{ ansible_os_family | lower }}-{{ ansible_distribution_major_version | lower }}.yml"
    - "{{ ansible_distribution | lower }}.yml"
    - "{{ ansible_os_family | lower }}.yml"

- name: "Check gitea version"
  shell: "set -eo pipefail; /usr/local/bin/gitea -v | cut -d' ' -f 3"
  args:
    executable: /bin/bash
  register: gitea_active_version
  changed_when: false
  failed_when: false
  when: gitea_version_check|bool

- name: backup gitea before update
  include_tasks: backup.yml
  when: gitea_backup_on_upgrade|bool

- name: install or update gitea
  include_tasks: install.yml

- include: create_user.yml

- name: "Create config directory"
  file:
    path: "{{ item }}"
    state: directory
    owner: "{{ gitea_user }}"
    group: "{{ gitea_group }}"
    mode: '0755'
  with_items:
    - "/etc/gitea"

- name: "Create data directory"
  file:
    path: "{{ item }}"
    state: directory
    owner: "{{ gitea_user }}"
    group: "{{ gitea_group }}"
    mode: 'u=rwX,g=rX,o='
    recurse: true
  with_items:
    - "{{ gitea_home }}"
    - "{{ gitea_home }}/data"
    - "{{ gitea_home }}/custom"
    - "{{ gitea_home }}/custom/https"
    - "{{ gitea_home }}/custom/mailer"
    - "{{ gitea_home }}/indexers"
    - "{{ gitea_home }}/log"
    - "{{ gitea_repository_root }}"

- include: install_systemd.yml
  when: ansible_service_mgr == "systemd"

- include_tasks: jwt_secrets.yml

- include_tasks: gitea_secrets.yml

- name: "Configure gitea"
  template:
    src: gitea.ini.j2
    dest: /etc/gitea/gitea.ini
    owner: "{{ gitea_user }}"
    group: "{{ gitea_group }}"
    mode: 0600
  notify: "Restart gitea"

- name: "Service gitea"
  service:
    name: gitea
    state: started
    enabled: true
  when: ansible_service_mgr == "systemd"

- include: fail2ban.yml
  when: gitea_fail2ban_enabled|bool