---
- name: Provision game node
  hosts: game_nodes
  become: true
  vars:
    node_agent_user: hgc-node
    node_data_dir: /var/lib/hgc
    port_range_start: 25565
    port_range_end: 25664
  tasks:
    - name: Install Docker
      ansible.builtin.apt:
        name:
          - docker.io
        state: present
        update_cache: true

    - name: Create node agent user
      ansible.builtin.user:
        name: "{{ node_agent_user }}"
        system: true
        create_home: false

    - name: Create node data directory
      ansible.builtin.file:
        path: "{{ node_data_dir }}"
        state: directory
        owner: "{{ node_agent_user }}"
        group: "{{ node_agent_user }}"
        mode: "0750"

    - name: Open Minecraft host port range
      ansible.builtin.ufw:
        rule: allow
        port: "{{ port_range_start }}:{{ port_range_end }}"
        proto: tcp

    - name: Install node-agent systemd unit
      ansible.builtin.copy:
        dest: /etc/systemd/system/hgc-node-agent.service
        mode: "0644"
        content: |
          [Unit]
          Description=HexaHost GameCloud Node Agent
          After=network-online.target docker.service
          Wants=network-online.target

          [Service]
          Type=simple
          User={{ node_agent_user }}
          ExecStart=/usr/local/bin/hgc-node-agent
          Restart=on-failure
          Environment=NODE_DATA_DIR={{ node_data_dir }}

          [Install]
          WantedBy=multi-user.target
      notify: Reload systemd

  handlers:
    - name: Reload systemd
      ansible.builtin.systemd:
        daemon_reload: true
