---
- name: Setup SSH key authentication for browser host
 hosts: browser
 become: yes
 vars:
    target_user: ben
    ssh_key_comment: "ansible-generated-key"
  tasks:
    - name: Generate SSH key pair if it doesn't exist
      user:
        name: "{{ target_user }}"
        generate_ssh_key: yes
        ssh_key_bits: 4096
        ssh_key_comment: "{{ ssh_key_comment }}"
      become_user: "{{ target_user }}"

    - name: Get SSH public key content
      command: cat /home/{{ target_user }}/.ssh/id_rsa.pub
      register: ssh_public_key
      become_user: "{{ target_user }}"
      changed_when: false

    - name: Display SSH public key for manual configuration
      debug:
        msg: |
          SSH Public Key for {{ inventory_hostname }}:
          {{ ssh_public_key.stdout }}
          
          To complete key-based authentication setup:
          1. Copy the above public key to the target system's authorized_keys
          2. Or use ssh-copy-id command from this system:
             ssh-copy-id -i /home/{{ target_user }}/.ssh/id_rsa.pub {{ target_user }}@{{ inventory_hostname }}

    - name: Ensure .ssh directory exists for user
      file:
        path: /home/{{ target_user }}/.ssh
        state: directory
        owner: "{{ target_user }}"
        group: "{{ target_user }}"
        mode: '0700'

    - name: Configure SSH to prefer key authentication
      lineinfile:
        path: /etc/ssh/sshd_config
        regexp: '^PasswordAuthentication'
        line: 'PasswordAuthentication yes'
        backup: yes
      notify: restart sshd

    - name: Configure SSH to allow key authentication
      lineinfile:
        path: /etc/ssh/sshd_config
        regexp: '^PubkeyAuthentication'
        line: 'PubkeyAuthentication yes'
        backup: yes
      notify: restart sshd

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