- name: base | system setup | wireguard install
  package:
    name: "{{ wireguard_package }}"
    state: latest

- name: base | system setup | wireguard generate private key
  shell:
    cmd: umask 077 && wg genkey | tee privatekey | wg pubkey > publickey
    chdir: /etc/wireguard
    creates: /etc/wireguard/publickey
  when:
    - wg_privkey is not defined
    - wg_pubkey is not defined

- name: base | system setup | wireguard cat pubkey
  command: "cat /etc/wireguard/publickey"
  register: wg_publickkey
  when:
    - wg_pubkey is not defined

- name: base | system setup | wireguard output pubkey
  debug:
    var: wg_publickkey.stdout_lines
  when:
    - wg_pubkey is not defined

- name: base | system setup | wireguard pause
  pause:
    seconds: 120
    prompt: please copy pubkey to your wireguard server
  when:
    - wg_pubkey is not defined

- name: base | system setup | wireguard copy keys
  copy:
    content: "{{ item.key }}"
    dest: "{{ item.keyfile }}"
    mode: '0600'
  loop:
    - { key: "{{ wg_pubkey }}", keyfile: "/etc/wireguard/publickey" }
    - { key: "{{ wg_privkey }}", keyfile: "/etc/wireguard/privatekey" }
  when:
    - wg_pubkey is defined
    - wg_privkey is defined

- name: base | system setup | wireguard generate config
  template:
    dest: "/etc/wireguard/VPN.conf"
    src: client_VPN.conf.j2
    owner: root
    group: root
    mode: '0600'

- name: base | system setup | wireguard check if already running
  command: wg show
  register: wireguard

- block:
  - name: base | system setup | wireguard start vpn
    command: wg-quick up VPN

  - name: base | system setup | wireguard enable service
    service:
      name: "wg-quick@VPN"
      enabled: true
  when: wireguard.stdout == ""
  ignore_errors: True