---
# Bootstrap remote Debian host for Veza V5 Ultra deployment
# Ensures python3, sudo, and essential tools are available

- name: Bootstrap Debian host for Veza deployment
  hosts: edge
  gather_facts: false
  become: true

  pre_tasks:
    - name: Install essential packages
      raw: |
        apt-get update && apt-get install -y \
          python3 \
          python3-pip \
          sudo \
          curl \
          gnupg \
          net-tools \
          ca-certificates \
          apt-transport-https \
          lsb-release \
          wget \
          unzip \
          git \
          vim \
          htop \
          iotop \
          nethogs

    - name: Ensure python3 is available
      raw: which python3
      register: python3_check
      failed_when: false

    - name: Create symlink for python if needed
      raw: ln -sf /usr/bin/python3 /usr/bin/python
      when: python3_check.rc != 0

    - name: Install additional packages
      raw: |
        apt-get install -y \
          python3-pip \
          python3-venv \
          snapd

    - name: Ensure user has sudo access
      raw: |
        if ! grep -q "senke ALL=(ALL) NOPASSWD:ALL" /etc/sudoers.d/senke; then
          echo "senke ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/senke
          chmod 440 /etc/sudoers.d/senke
        fi

    - name: Configure SSH for better performance
      lineinfile:
        path: /etc/ssh/sshd_config
        regexp: "{{ item.regexp }}"
        line: "{{ item.line }}"
        state: present
      loop:
        - { regexp: "^#?ClientAliveInterval", line: "ClientAliveInterval 60" }
        - { regexp: "^#?ClientAliveCountMax", line: "ClientAliveCountMax 3" }
        - { regexp: "^#?TCPKeepAlive", line: "TCPKeepAlive yes" }
      notify: restart ssh

    - name: Ensure SSH service is enabled and running
      systemd:
        name: ssh
        state: started
        enabled: true

    - name: Install UFW
      apt:
        name: ufw
        state: present

    - name: Configure firewall for Veza ports
      community.general.ufw:
        rule: allow
        port: "{{ item }}"
        proto: tcp
      loop:
        - "22"    # SSH
        - "80"    # HTTP
        - "443"   # HTTPS
        - "8080"  # Backend API
        - "8081"  # Chat WebSocket
        - "8082"  # Stream HLS

    - name: Enable UFW
      community.general.ufw:
        state: enabled
        policy: deny

  handlers:
    - name: restart ssh
      systemd:
        name: ssh
        state: restarted

  post_tasks:
    - name: Test connectivity
      ping:
