---

### tags:
###   update_config
###   update_deployment

- name: "Register wireguard peers"
  set_fact:
    wireguard_peers: "{{ wireguard_peers | default([]) + [ lookup('file', 'users/' + item + '/wireguard.yml') | from_yaml ] }}"
  loop: '{{ smardigo_platform_users }}'
  when: "('users/' ~ item ~ '/wireguard.yml') is file"

- name: "Print wireguard peers"
  debug: var=wireguard_peers
 
- name: "Register source IPs"
  set_fact:
    source_ips: "{{ (wireguard_peers | selectattr('source_ip', 'defined') | map(attribute='source_ip') | list) }}"

- name: "Assert no duplicate source IPs"
  assert:
    that: "{{ source_ips|length == source_ips|unique|length }}"
    fail_msg: "Detected duplicate source IPs {{ source_ips }}"

- name: "Check if {{ wireguard_id }}/docker-compose.yml exists"
  stat:
    path: '{{ service_base_path }}/{{ wireguard_id }}/docker-compose.yml'
  register: check_docker_compose_file
  tags:
    - update_config
    - update_deployment

- name: "Stop {{ wireguard_id }}"
  community.docker.docker_compose:
    project_src: '{{ service_base_path }}/{{ wireguard_id }}'
    state: absent
  when: check_docker_compose_file.stat.exists
  tags:
    - update_config
    - update_deployment

- name: "Deploy docker templates for {{ wireguard_id }}"
  include_role:
    name: hetzner-ansible-sma-deploy
    tasks_from: templates
  vars:
    current_config: "_docker"
    current_base_path: "{{ service_base_path }}"
    current_destination: "{{ wireguard_id }}"
    current_owner: "{{ docker_owner }}"
    current_group: "{{ docker_group }}"
    current_docker: "{{ wireguard_docker }}"
  tags:
    - update_config

- name: "Deploy service templates for {{ wireguard_id }}"
  include_role:
    name: hetzner-ansible-sma-deploy
    tasks_from: templates
  vars:
    current_config: "wireguard"
    current_base_path: "{{ service_base_path }}"
    current_destination: "{{ wireguard_id }}"
    current_owner: "{{ docker_owner }}"
    current_group: "{{ docker_group }}"
  tags:
    - update_config

- name: "Add wireguard kernel module"
  community.general.modprobe:
    name: wireguard
    state: present
  become: true

- name: "Activate dynamic debug log for wireguard" # noqa command-instead-of-shell
  shell: |
    set -o pipefail 
    echo module wireguard +p | sudo tee /sys/kernel/debug/dynamic_debug/control
  args:
    executable: /bin/bash
  changed_when: false
  become: true
