---
- name: Ensure binary is present
  ansible.builtin.get_url:
    url: 'https://git.rustybever.be/api/packages/Chewing_Bever/generic/otter/0.3.0/otter-linux-amd64'
    dest: '/usr/local/bin/otter'
    owner: 'root'
    group: 'root'
    mode: '755'
  notify: 'restart otter'

- name: Ensure system group exists
  ansible.builtin.group:
    name: 'otter'
    gid: 204
    system: true
    state: present

- name: Ensure system user exists
  ansible.builtin.user:
    name: 'otter'
    group: 'otter'
    uid: 204
    system: true
    create_home: false

- name: Ensure permissions are correct
  ansible.builtin.file:
    path: "{{ data_dir }}"
    state: directory
    mode: '0755'
    owner: '204'
    group: '204'

- name: Ensure configuration directory is present
  ansible.builtin.file:
    path: '/etc/otter'
    state: directory
    mode: '0755'

- name: Ensure config file is present
  ansible.builtin.template:
    src: 'otter.toml.j2'
    dest: '/etc/otter/otter.toml'
    mode: '0644'
    owner: 'root'
    group: 'root'
  notify: 'restart otter'

- name: Ensure Caddyfile is present
  ansible.builtin.copy:
    src: 'otter.Caddyfile'
    dest: '/etc/caddy/otter.Caddyfile'
    owner: root
    group: root
    mode: '0644'
  notify: reload caddy

# - name: Ensure backup scripts are present
#   ansible.builtin.copy:
#     src: "otter.{{ item }}.backup.sh"
#     dest: "/etc/backups/otter.{{ item }}.backup.sh"
#     owner: 'root'
#     group: 'root'
#     mode: '0644'
#   loop:
#     - 'data'

- name: Ensure service file is present
  ansible.builtin.copy:
    src: 'otter.service'
    dest: '/lib/systemd/system/otter.service'
    owner: 'root'
    group: 'root'
    mode: '0644'
  register: res

- name: systemd-reload
  ansible.builtin.systemd_service:
    daemon_reload: true
  when: 'res.changed'

- name: Ensure otter service is enabled
  ansible.builtin.service:
    name: 'otter'
    enabled: true
