---
- name: Validate SSH_PORT environment variable
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Check SSH_PORT is set
      ansible.builtin.fail:
        msg: "SSH_PORT environment variable is not set"
      when: lookup('env', 'SSH_PORT') == ''
      tags: [bootstrap, ssh]

    - name: Validate SSH_PORT is a valid port number
      ansible.builtin.fail:
        msg: "SSH_PORT must be between 1 and 65535, got: {{ lookup('env', 'SSH_PORT') }}"
      when: >
        lookup('env', 'SSH_PORT') | int < 1 or
        lookup('env', 'SSH_PORT') | int > 65535
      tags: [bootstrap, ssh]

- name: Bootstrap new VPS - Initial secure setup with dual-user
  hosts: vps
  remote_user: "{{ ansible_user }}"
  become: true
  gather_facts: true
  vars:
    ansible_port: 22
  tasks:
    - name: Set hostname to inventory name
      ansible.builtin.hostname:
        name: "{{ inventory_hostname }}"
      tags: [bootstrap, system, hostname]

    - name: Add hostname to /etc/hosts
      ansible.builtin.lineinfile:
        path: /etc/hosts
        regexp: '^127\.0\.1\.1'
        line: "127.0.1.1 {{ inventory_hostname }}"
        state: present
      tags: [bootstrap, system, hostname]

  roles:
    # Set up dual-user system first
    - role: ansible_user
      tags: [bootstrap, users, ansible-user]
    # Configure firewall rules (not enabled yet - prevents lockout)
    - role: ufw
      tags: [bootstrap, security, firewall, ufw]
    # Change SSH port, validate, then enable firewall
    - role: ssh
      tags: [bootstrap, security, network, ssh]

- name: Update connection settings for subsequent plays
  hosts: vps
  gather_facts: false
  tasks:
    - name: Set ansible_port to new SSH port for this session
      ansible.builtin.set_fact:
        ansible_port: "{{ lookup('env', 'SSH_PORT') }}"
        cacheable: false
      tags: [bootstrap, ssh]

    - name: Switch to ansible automation user for subsequent plays
      ansible.builtin.set_fact:
        ansible_user: ansible
        cacheable: false
      tags: [bootstrap, users]
