---
- name: Ensure tuwunel is installed
  ansible.builtin.apt:
    deb: 'https://github.com/matrix-construct/tuwunel/releases/download/v1.5.0/v1.5.0-release-all-x86_64-v3-linux-gnu-tuwunel.deb'

- name: Ensure system group exists
  ansible.builtin.group:
    name: 'tuwunel'
    gid: 205
    system: true
    state: present

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

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

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

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

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

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

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

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