# Provision the dedicated coturn (TURN/STUN) droplet for WebRTC mesh voice —
# Phase C of the my-sea invite/voice sprint. Mirrors the PySwiss split: its own
# DigitalOcean droplet, NOT the app box. CI needs none of this (signaling tests
# use the in-memory channel layer; the TURN endpoint is unit-tested w. a fake
# secret) — this runs only when you actually stand voice up on staging/prod.
#
# Prereqs (manual, one-time):
#   1. Create a DO droplet + a reserved/static public IP; point
#      turn.earthmanrpg.me at it.
#   2. Add it to inventory.ini under [coturn] with host_vars:
#        coturn_secret, coturn_realm, coturn_public_ip[, coturn_private_ip,
#        coturn_tls_cert, coturn_tls_key]
#   3. Put the SAME coturn_secret into the APP droplet's env as
#      COTURN_SHARED_SECRET (+ COTURN_TURN_HOST=turn.earthmanrpg.me,
#      COTURN_REALM) so the /api/voice/turn-credentials/ HMAC matches.
#
# Run:  ansible-playbook -i inventory.ini coturn-playbook.yaml
#
# nginx already proxy-upgrades WebSocket on the APP droplet (nginx.conf.j2), so
# ws/voice/ rides the existing proxy — no nginx change here.
- hosts: coturn
  become: true

  tasks:
    - name: Install coturn
      ansible.builtin.apt:
        name: coturn
        state: latest
        update_cache: true

    - name: Enable the coturn daemon
      ansible.builtin.lineinfile:
        path: /etc/default/coturn
        regexp: '^#?TURNSERVER_ENABLED='
        line: 'TURNSERVER_ENABLED=1'

    - name: Ensure turn log dir exists
      ansible.builtin.file:
        path: /var/log/turnserver
        state: directory
        owner: turnserver
        group: turnserver
        mode: '0755'

    - name: Deploy turnserver.conf
      ansible.builtin.template:
        src: coturn.conf.j2
        dest: /etc/turnserver.conf
        mode: '0640'
      notify: Restart coturn

    - name: Open STUN/TURN signaling ports (3478 udp+tcp)
      community.general.ufw:
        rule: allow
        port: '3478'
        proto: "{{ item }}"
      loop: [udp, tcp]

    - name: Open TURN-over-TLS port (5349 tcp)
      community.general.ufw:
        rule: allow
        port: '5349'
        proto: tcp

    - name: Open the relay UDP port range (49152-65535)
      community.general.ufw:
        rule: allow
        port: '49152:65535'
        proto: udp

    - name: Enable + start coturn
      ansible.builtin.systemd:
        name: coturn
        enabled: true
        state: started

  handlers:
    - name: Restart coturn
      ansible.builtin.systemd:
        name: coturn
        state: restarted
