---
- name: Install dependencies
  ansible.builtin.apt:
    pkg:
      - git
      - git-lfs
    update_cache: true
  become: true

- name: Make forgejo group
  ansible.builtin.group:
    name: forgejo
  become: true

- name: Make forgejo user
  ansible.builtin.user:
    name: forgejo
    group: forgejo
    password: "!"
    home: "/home/forgejo"
    create_home: true
    system: true
    shell: /bin/bash
    comment: "forgejo system user"
  become: true

- name: Make forgejo dir
  ansible.builtin.file:
    state: directory
    path: /usr/local/bin/forgejo
    owner: forgejo
    mode: "755"
  become: true

- name: Download forgejo
  ansible.builtin.get_url:
    dest: /usr/local/bin/forgejo/forgejo
    url: "{{ forgejo_binary_download }}"
    checksum: "{{ forgejo_sha1 }}"
    owner: forgejo
    mode: "0755"
  become: true
  notify: Restart forgejo

- name: Create forgejo logging dir
  ansible.builtin.file:
    path: /var/log/forgejo
    owner: forgejo
    mode: "0755"
    state: directory
  become: true

- name: Create forgejo data dir
  ansible.builtin.file:
    state: directory
    owner: forgejo
    group: forgejo
    mode: "0750"
    path: /var/lib/forgejo
  become: true
  notify: Restart forgejo

- name: Make forgejo config dir
  ansible.builtin.file:
    path: /etc/forgejo
    owner: root
    group: forgejo
    mode: "0770"
    state: directory
  become: true
  notify: Restart forgejo

- name: Transfer forgejo config
  ansible.builtin.template:
    src: app.ini.j2
    dest: /etc/forgejo/app.ini
    owner: root
    mode: "0440"
  become: true
  notify: Restart forgejo

- name: Copy forgejo service
  ansible.builtin.copy:
    src: forgejo.service
    dest: /etc/systemd/system/forgejo.service
    mode: "0644"
    owner: root
    group: root
  become: true
  notify: Restart forgejo

- name: Ensure forgejo service started
  ansible.builtin.service:
    name: forgejo
    state: started
    enabled: true
  become: true

- name: Sync custom forgejo styling
  ansible.posix.synchronize:
    src: custom
    dest: /usr/local/bin/forgejo/
    rsync_opts:
      - --chown=forgejo:forgejo
      - --chmod=755
    recursive: true
  notify: Restart forgejo
  become: true

- name: Make forgejo config dir non writeable
  ansible.builtin.file:
    path: /etc/forgejo
    mode: "0750"
    state: directory
  become: true
  notify: Restart forgejo
  when: "not initial_run"

- name: Copy forgejo nginx config
  ansible.builtin.copy:
    src: forgejo.conf
    dest: /etc/nginx/sites-enabled/forgejo.conf
    owner: root
    mode: "0644"
  become: true
  notify: Reload nginx
