---
- 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: "/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://codeberg.org/forgejo/forgejo/releases/download/v1.21.1-0/forgejo-1.21.1-0-linux-arm64
      checksum: sha256:0d7e22ab2554b250cb9fb080ce2b14fde081029648bb7bbdcbd085c97a559535
      dest: /usr/local/bin/forgejo
      mode: '775'
      owner: git
      group: git
    become: true

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

  - name: robots.txt
    ansible.builtin.template:
      src: templates/forgejo/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: forgejo
      enabled: true
      daemon_reload: true
    become: true
