---
# Playbook 01: Preflight Checks
# Validates environment before deployment

- name: Preflight Checks
  hosts: all
  gather_facts: yes
  become: no
  
  tasks:
    - name: Check Ansible version
      assert:
        that:
          - ansible_version.full is version('2.14', '>=')
        fail_msg: "Ansible 2.14 or higher is required"
        success_msg: "Ansible version OK ({{ ansible_version.full }})"
      delegate_to: localhost
      run_once: true

    - name: Test SSH connectivity
      ping:

    - name: Check sudo access
      command: sudo -n true
      changed_when: false

    - name: Check Python3 availability
      command: python3 --version
      register: python_version
      changed_when: false

    - name: Display Python version
      debug:
        msg: "Python version: {{ python_version.stdout }}"

    - name: Check disk space
      shell: df -h / | awk 'NR==2 {print $4}'
      register: disk_space
      changed_when: false

    - name: Validate sufficient disk space
      assert:
        that:
          - disk_space.stdout is regex('[0-9]+G')
        fail_msg: "Insufficient disk space. At least 20GB recommended."
        success_msg: "Disk space OK ({{ disk_space.stdout }} available)"

    - name: Check if ports 80 and 443 are available
      wait_for:
        port: "{{ item }}"
        state: stopped
        timeout: 1
      loop:
        - 80
        - 443
      ignore_errors: yes
      register: port_check

    - name: Detect virtualization type
      command: systemd-detect-virt
      register: virt_type
      changed_when: false
      failed_when: false

    - name: Warn if running in LXC
      debug:
        msg: |
          ⚠️  RUNNING IN LXC CONTAINER
          Docker requires nested virtualization.
          Ensure on LXC host: lxc config set {{ inventory_hostname }} security.nesting true
      when: "'lxc' in virt_type.stdout"

    - name: Validate DNS resolution for all subdomains
      command: dig +short {{ item }}.{{ domain }} @8.8.8.8
      register: dns_check
      changed_when: false
      failed_when: false
      loop:
        - "{{ subdomain_nextcloud }}"
        - "{{ subdomain_office }}"
        - "{{ subdomain_draw }}"
        - "{{ subdomain_notes }}"
        - "{{ subdomain_homarr }}"
        - "{{ subdomain_dockhand }}"
        - "{{ subdomain_uptime }}"

    - name: Display DNS check results
      debug:
        msg: "{{ item.item }}.{{ domain }} → {{ item.stdout if item.stdout else 'NOT CONFIGURED' }}"
      loop: "{{ dns_check.results }}"
      loop_control:
        label: "{{ item.item }}.{{ domain }}"

    - name: Preflight checks complete
      debug:
        msg: |
          ✓ All preflight checks passed
          ✓ Ready to proceed with deployment
