---
# Semaphore Survey vars required:
#   vm_ip   (e.g. 192.168.1.22)
#   vm_user (e.g. craig)
#   vm_pass (password for vm_user, and sudo)
#
# This playbook connects using PASSWORD SSH (based on the survey vars),
# then creates an SSHD override drop-in to enable PasswordAuthentication.

- name: Build runtime target from Survey variables
  hosts: localhost
  gather_facts: false

  tasks:
    - name: Validate required inputs
      ansible.builtin.assert:
        that:
          - vm_ip is defined
          - vm_user is defined
          - vm_pass is defined
        fail_msg: "Missing vm_ip, vm_user or vm_pass in Task Template Survey."

    - name: Add VM as runtime host (password SSH)
      ansible.builtin.add_host:
        name: target_vm
        groups: runtime
        ansible_host: "{{ vm_ip }}"
        ansible_user: "{{ vm_user }}"
        ansible_password: "{{ vm_pass }}"
        ansible_become: true
        ansible_become_password: "{{ vm_pass }}"
        ansible_ssh_common_args: >-
          -o PreferredAuthentications=password
          -o PubkeyAuthentication=no
          -o IdentitiesOnly=yes
          -o StrictHostKeyChecking=no
          -o UserKnownHostsFile=/dev/null

    - name: Show target
      ansible.builtin.debug:
        msg: "Targeting {{ vm_user }}@{{ vm_ip }} (password SSH)"

- name: Enable SSH PasswordAuthentication (override drop-in)
  hosts: runtime
  become: true
  gather_facts: false

  tasks:
    - name: Create SSH override to allow password auth
      ansible.builtin.copy:
        dest: /etc/ssh/sshd_config.d/99-semaphore-passwordauth.conf
        owner: root
        group: root
        mode: "0644"
        content: |
          PasswordAuthentication yes

    - name: Validate sshd configuration
      ansible.builtin.command: sshd -t
      changed_when: false

    - name: Restart SSH service (Ubuntu/Debian)
      ansible.builtin.service:
        name: ssh
        state: restarted

    - name: Confirm effective PasswordAuthentication setting
      ansible.builtin.shell: |
        set -e
        sshd -T | grep -i '^passwordauthentication'
      args:
        executable: /bin/bash
      register: sshd_effective
      changed_when: false

    - name: Show effective setting
      ansible.builtin.debug:
        var: sshd_effective.stdout
