---
- name: Ensure WireGuard is installed
  ansible.builtin.apt:
    name: wireguard
    state: present

- name: Ensure /etc/wireguard directory exists
  ansible.builtin.file:
    path: /etc/wireguard
    state: directory
    owner: root
    group: root
    mode: "700"

- name: Check if private key already exists
  ansible.builtin.stat:
    path: /etc/wireguard/private_key
  register: wireguard_private_key_file

- name: Generate WireGuard private key
  ansible.builtin.shell: wg genkey > /etc/wireguard/private_key
  when: not wireguard_private_key_file.stat.exists

- name: Set permissions on private key
  ansible.builtin.file:
    path: /etc/wireguard/private_key
    owner: root
    group: root
    mode: "600"

- name: Derive and write WireGuard public key from private key
  ansible.builtin.shell: wg pubkey < /etc/wireguard/private_key > /etc/wireguard/public_key
  changed_when: false

- name: Set permissions on public key
  ansible.builtin.file:
    path: /etc/wireguard/public_key
    owner: root
    group: root
    mode: "644"

- name: Read WireGuard private key
  ansible.builtin.slurp:
    src: /etc/wireguard/private_key
  register: wireguard_private_key_b64

- name: Set WireGuard private key fact
  ansible.builtin.set_fact:
    wireguard_private_key: "{{ wireguard_private_key_b64.content | b64decode | trim }}"

- name: Read WireGuard public key
  ansible.builtin.slurp:
    src: /etc/wireguard/public_key
  register: wireguard_public_key_b64

- name: Set WireGuard public key fact
  ansible.builtin.set_fact:
    wireguard_public_key: "{{ wireguard_public_key_b64.content | b64decode | trim }}"

- name: Deploy WireGuard interface config
  ansible.builtin.template:
    src: wg0.conf.j2
    dest: "/etc/wireguard/{{ wireguard_interface }}.conf"
    owner: root
    group: root
    mode: "600"
  notify: restart wg-quick

- name: Enable and start wg-quick service
  ansible.builtin.service:
    name: "wg-quick@{{ wireguard_interface }}"
    state: started
    enabled: true
