---
- name: Setup complete SSH key authentication for browser host
  hosts: browser
  become: yes
  vars:
    target_user: ben
    ssh_key_comment: "ansible-generated-key-for-{{ inventory_hostname }}"

  tasks:
    - name: Copy existing Ed25519 SSH public key to target user
      copy:
        src: /root/.ssh/id_ed25519.pub
        dest: /home/{{ target_user }}/.ssh/id_ed25519.pub
        owner: "{{ target_user }}"
        group: "{{ target_user }}"
        mode: '0644'

    - name: Copy existing Ed25519 SSH private key to target user
      copy:
        src: /root/.ssh/id_ed25519
        dest: /home/{{ target_user }}/.ssh/id_ed25519
        owner: "{{ target_user }}"
        group: "{{ target_user }}"
        mode: '0600'

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

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

    - name: Add public key to authorized_keys
      authorized_key:
        user: "{{ target_user }}"
        state: present
        key: "{{ ssh_public_key.stdout }}"
      become_user: "{{ target_user }}"

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

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

    - name: Configure SSH authorized keys file permissions
      file:
        path: /home/{{ target_user }}/.ssh/authorized_keys
        owner: "{{ target_user }}"
        group: "{{ target_user }}"
        mode: '0600'

    - name: Display success message
      debug:
        msg: "SSH key authentication has been configured for user {{ target_user }} on {{ inventory_hostname }}"

  handlers:
    - name: restart sshd
      systemd:
        name: sshd
        state: restarted
      when: ansible_connection != 'local'