---
- hosts: [wireguard]
  tasks:
    - name: Install wireguard packages
      become: true
      ansible.builtin.apt:
        name: wireguard
        state: present

    - name: Generate keys
      become: true
      ansible.builtin.shell: |
        umask 0077
        wg genkey > /etc/wireguard/privatekey
        wg pubkey < /etc/wireguard/privatekey > /etc/wireguard/publickey
      args:
        creates:
          - /etc/wireguard/privatekey
          - /etc/wireguard/publickey

    - name: Register public key
      become: true
      ansible.builtin.shell: cat /etc/wireguard/publickey
      register: wireguard_public_key
      changed_when: false

    - name: Register private key
      become: true
      ansible.builtin.shell: cat /etc/wireguard/privatekey
      register: wireguard_private_key
      changed_when: false

    - name: Setup network device
      become: yes
      notify: systemd network restart
      ansible.builtin.template:
        src: ./templates/wireguard/wg0.netdev.j2
        dest: /etc/systemd/network/wg0.netdev
        owner: root
        group: systemd-network
        mode: 0640

    - name: Setup network
      become: yes
      notify: systemd network restart
      ansible.builtin.template:
        src: ./templates/wireguard/wg0.network.j2
        dest: /etc/systemd/network/wg0.network
        owner: root
        group: systemd-network
        mode: 0640

  handlers:
    - name: systemd network restart
      become: true
      ansible.builtin.service:
        name: systemd-networkd
        state: restarted
        enabled: true
