- name: Ensure download directory is present
  ansible.builtin.file:
    path: "/opt/restic-rest-{{ restic_rest_version }}"
    state: directory
    mode: '0755'

- name: Ensure binary is downloaded
  ansible.builtin.unarchive:
    src: "https://github.com/restic/rest-server/releases/download/v{{ restic_rest_version }}/rest-server_{{ restic_rest_version }}_linux_amd64.tar.gz"
    remote_src: true
    dest: "opt/restic-rest-{{ restic_rest_version }}"
    creates: "opt/restic-rest-{{ restic_rest_version }}/rest-server_{{ restic_rest_version }}_linux_amd64/rest-server"
    include:
      - "rest-server_{{ restic_rest_version }}_linux_amd64/rest-server"
  register: res

- name: Ensure binary is copied to correct location
  ansible.builtin.copy:
    src: "/opt/restic-rest-{{ restic_rest_version }}/rest-server_{{ restic_rest_version }}_linux_amd64/rest-server"
    remote_src: true
    dest: '/usr/local/bin/restic-rest-server'
    owner: 'root'
    group: 'root'
    mode: '0755'
  when: 'res.changed'
  notify: 'restart restic-rest-server'

- name: Ensure system group exists
  ansible.builtin.group:
    name: 'restic'
    gid: 202
    system: true
    state: present

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

- name: Ensure data subvolume permissions are correct
  ansible.builtin.file:
    path: '{{ restic_rest_data_dir }}'
    state: directory
    mode: '0755'
    owner: 'restic'
    group: 'restic'

- name: Ensure service file is present
  ansible.builtin.template:
    src: 'restic-rest-server.service.j2'
    dest: '/lib/systemd/system/restic-rest-server.service'
    owner: 'root'
    group: 'root'
    mode: '0644'
  notify: 'restart restic-rest-server'
