---
- name: Install WireGuard
  ansible.builtin.dnf:
    name: wireguard-tools
    state: present

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

- name: Check if WireGuard private key exists
  ansible.builtin.stat:
    path: /etc/wireguard/private.key
  register: wg_key_stat

- name: Generate WireGuard keypair
  ansible.builtin.shell: |
    wg genkey | tee /etc/wireguard/private.key | wg pubkey > /etc/wireguard/public.key
    chmod 600 /etc/wireguard/private.key
    chmod 644 /etc/wireguard/public.key
  when: not wg_key_stat.stat.exists

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

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

- name: Set WireGuard key facts
  ansible.builtin.set_fact:
    wg_server_private_key: "{{ wg_private_key_raw.content | b64decode | trim }}"
    wg_server_public_key: "{{ wg_public_key_raw.content | b64decode | trim }}"

- name: Deploy wg0.conf
  ansible.builtin.template:
    src: wg0.conf.j2
    dest: "/etc/wireguard/{{ wireguard_interface }}.conf"
    mode: "0600"
    owner: root
    group: root
  notify: restart wireguard

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

- name: Allow WireGuard UDP port from admin CIDRs
  ansible.posix.firewalld:
    rich_rule: >-
      rule family="ipv4" source address="{{ item }}"
      port port="{{ wireguard_port }}" protocol="udp" accept
    zone: drop
    state: enabled
    permanent: true
    immediate: true
  loop: "{{ admin_allowed_cidrs.split(' ') }}"

- name: Allow DB ports from WireGuard subnet only
  ansible.posix.firewalld:
    rich_rule: >-
      rule family="ipv4" source address="{{ wireguard_subnet }}"
      port port="{{ item }}" protocol="tcp" accept
    zone: drop
    state: enabled
    permanent: true
    immediate: true
  loop:
    - "{{ wireguard_db_pg_proxy_port }}"
    - "{{ wireguard_db_mongo_proxy_port }}"

- name: Print server public key (client config için gerekli)
  ansible.builtin.debug:
    msg: "WireGuard server public key: {{ wg_server_public_key }}"
