---
# Distribute SSH Public Key to All Devices
# ─────────────────────────────────────────
# Purpose : Push the monitoring server's public key to every device so that
#           all subsequent Ansible playbooks can use key-based authentication.
#
# Auth    : Connects with ansible_password (set via --extra-vars at runtime).
#           No SSH key is required on the target to run this playbook.
#
# Run via : Ansible > SSH Setup > "Deploy SSH Keys to All Devices" button, or
#           POST /api/ansible/ssh/distribute-keys
#
# After   : Disable "Use password authentication" in SSH Settings so all other
#           playbooks switch back to key-based auth automatically.

- name: Distribute SSH Public Key to All Devices
  hosts: all
  gather_facts: false
  become: false

  tasks:

    - name: Ensure .ssh directory exists with correct permissions
      file:
        path: /home/pi/.ssh
        state: directory
        mode: '0700'
        owner: pi
        group: pi

    - name: Deploy controller public key to authorized_keys
      authorized_key:
        user: pi
        key: "{{ lookup('file', playbook_dir + '/../ssh_keys/app_key.pub') }}"
        state: present
        exclusive: false

    - name: Set correct permissions on authorized_keys
      file:
        path: /home/pi/.ssh/authorized_keys
        mode: '0600'
        owner: pi
        group: pi

    - name: Count keys in authorized_keys
      shell: grep -c "" /home/pi/.ssh/authorized_keys
      register: key_count
      changed_when: false

    - name: Confirm successful deployment
      debug:
        msg: >-
          SSH key deployed on {{ inventory_hostname }} ({{ ansible_host }}).
          authorized_keys now contains {{ key_count.stdout }} key(s).
          Key-based authentication is ready.
