---
- name: Install and deploy gitea
  hosts: ulna

  tasks:
  - name: Ensure git is installed
    ansible.builtin.apt:
      name: git
      state: present
    become: true

  - name: Create git group
    ansible.builtin.group:
      name: git
      state: present
    become: true

  - name: Create git user
    ansible.builtin.user:
      name: git
      comment: Git user
      group: git
      shell: /bin/bash
      password: '!'
      home: /home/git
      create_home: true
    become: true

  - name: Create required directories
    ansible.builtin.file:
      path: "{{ item.dir }}"
      mode: "{{ item.mode }}"
      owner: "{{ item.owner }}"
      group: "{{ item.group }}"
      state: directory
    loop:
      - { dir: "/opt/gitea", owner: "git", group: "git", mode: "0750" }
      - { dir: "/var/lib/gitea/custom", owner: "git", group: "git", mode: "0750" }
      - { dir: "/var/lib/gitea/data", owner: "git", group: "git", mode: "0750" }
      - { dir: "/var/lib/gitea/log", owner: "git", group: "git", mode: "0750" }
      - { dir: "/etc/gitea", owner: "root", group: "git", mode: "0770" }
    become: true

  - name: Download gitea
    ansible.builtin.get_url:
      url: https://github.com/go-gitea/gitea/releases/download/v1.20.4/gitea-1.20.4-linux-arm64
      checksum: sha256:e173e434d0afaf5c87e7b3dcda8d3e5946c82324879e926baa289509170c1211
      dest: /opt/gitea/gitea
      mode: '775'
      owner: git
      group: git
    become: true

  - name: Service file
    ansible.builtin.template:
      src: templates/gitea/gitea.service.j2
      dest: /etc/systemd/system/gitea.service
    become: true

  - name: robots.txt
    ansible.builtin.template:
      src: templates/gitea/robots.txt.j2
      dest: /var/lib/gitea/custom/robots.txt
      owner: git
    become: true

  - name: (Re)start the systemd service
    ansible.builtin.systemd:
      state: restarted
      name: gitea
      enabled: true
      daemon_reload: true
    become: true
