---
- name: Ensure newest binary is present
  ansible.builtin.get_url:
    url: "https://git.rustybever.be/api/packages/Chewing_Bever/generic/lander/{{ lander_version }}/lander-linux-{{ 'arm64' if ansible_architecture == 'aarch64' else 'amd64' }}"
    dest: '/usr/local/bin/lander'
    owner: 'root'
    group: 'root'
    mode: '0755'
  notify: 'restart lander'

- name: Ensure system group exists
  ansible.builtin.group:
    name: 'lander'
    gid: 201
    system: true
    state: present

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

- name: Ensure data directory is present
  ansible.builtin.file:
    path: '/mnt/data1/lander'
    state: directory
    mode: '0755'
    owner: 'root'
    group: 'root'

# Only one BTRFS file system should be mounted, so this will match that one
- name: Ensure data subvolume is present
  community.general.btrfs_subvolume:
    name: '/lander/{{ item }}'
  loop:
    - 'data'

- name: Ensure data subvolume permissions are correct
  ansible.builtin.file:
    path: '/mnt/data1/lander/{{ item }}'
    state: directory
    mode: '0755'
    owner: 'lander'
    group: 'lander'
  loop:
    - 'data'

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

- name: Ensure environment file is present
  ansible.builtin.template:
    src: 'lander.env.j2'
    dest: '/etc/lander/lander.env'
    owner: 'lander'
    group: 'lander'
    mode: '0644'
  notify: 'restart lander'

- name: Ensure backup script is present
  ansible.builtin.copy:
    src: 'lander.{{ item }}.backup.sh'
    dest: '/etc/backups/lander.{{ item }}.backup.sh'
    owner: 'root'
    group: 'root'
    mode: '0644'
  loop:
    - 'data'

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

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

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

- name: Ensure lander service is enabled
  ansible.builtin.service:
    name: 'lander'
    state: 'started'
    enabled: true
