---
- name: Validate bootstrap configuration
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Check hostname is set
      ansible.builtin.fail:
        msg: "hostname is not configured. Run: auberge config set hostname <HOSTNAME>"
      when: hostname is not defined or hostname == ''
      tags: [bootstrap, system, hostname]

    - name: Check ssh_port is set
      ansible.builtin.fail:
        msg: "ssh_port is not configured. Run: auberge config set ssh_port <PORT>"
      when: ssh_port is not defined or 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: {{ ssh_port }}"
      when: >
        ssh_port | int < 1 or
        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
      ansible.builtin.hostname:
        name: "{{ hostname }}"
      tags: [bootstrap, system, hostname]

    - name: Ensure localhost resolves to 127.0.0.1
      ansible.builtin.lineinfile:
        path: /etc/hosts
        regexp: '^127\.0\.0\.1\s'
        line: "127.0.0.1\tlocalhost"
        state: present
      tags: [bootstrap, system, hostname]

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

  roles:
    - role: ansible_user
      tags: [bootstrap, users, ansible-user]
    - role: ufw
      tags: [bootstrap, security, firewall, ufw]
    - 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: "{{ 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]
