---
- name: Phase 1 - Bootstrap SSH Keys and Packages
  hosts: linux
  remote_user: root
  vars_files:
    - vault.yml
  tasks:
    - name: Ensure .ssh directory exists
      file:
        path: /root/.ssh
        state: directory
        mode: '0700'

    - name: Deploy SSH Identity (Private and Public Keys)
      copy:
        dest: "/root/.ssh/{{ item.file }}"
        content: "{{ item.content }}"
        mode: "{{ item.mode }}"
      loop:
        - { file: 'id_ed25519', content: "{{ my_private_key }}", mode: '0400' }
        - { file: 'id_ed25519.pub', content: "{{ my_public_key }}", mode: '0644' }
      when: my_private_key is defined

    - name: Authorize Public Key for Root
      authorized_key:
        user: root
        key: "{{ my_public_key }}"
      when: my_public_key is defined

    - name: Configure Passwordless Sudo for Zeshan
      copy:
        dest: /etc/sudoers.d/zeshan
        content: "zeshan ALL=(ALL) NOPASSWD: ALL"
        mode: '0440'

- name: Phase 2 - Secure SSH Port
  hosts: linux
  become: yes
  vars:
    new_ssh_port: 54321
  tasks:
    - name: Handle SELinux for custom SSH port (RHEL)
      block:
        - name: Install SELinux management tools
          package:
            name: policycoreutils-python-utils
            state: present
        - name: Allow SSH on custom port in SELinux
          seport:
            ports: "{{ new_ssh_port }}"
            proto: tcp
            setype: ssh_port_t
            state: present
      when: ansible_os_family == 'RedHat'

    - name: Configure SSH Port in sshd_config
      lineinfile:
        path: /etc/ssh/sshd_config
        regexp: '^#?Port\s+'
        line: "Port {{ new_ssh_port }}"
      notify: Restart SSH

    - name: Handle Systemd Socket Activation (Debian/Ubuntu)
      block:
        - name: Check if SSH socket exists
          stat:
            path: /lib/systemd/system/ssh.socket
          register: ssh_socket_file

        - name: Create socket override directory
          file:
            path: /etc/systemd/system/ssh.socket.d
            state: directory
          when: ssh_socket_file.stat.exists

        - name: Set Port in Systemd Socket Override
          copy:
            dest: /etc/systemd/system/ssh.socket.d/addresses.conf
            content: |
              [Socket]
              ListenStream=
              ListenStream={{ new_ssh_port }}
          when: ssh_socket_file.stat.exists
          notify: 
            - Reload Systemd
            - Stop SSH Service
            - Restart SSH Socket

  handlers:
    - name: Reload Systemd
      systemd:
        daemon_reload: yes

    - name: Stop SSH Service
      service:
        name: ssh
        state: stopped
      when: ansible_os_family == 'Debian'

    - name: Restart SSH Socket
      service:
        name: ssh.socket
        state: restarted

    - name: Restart SSH
      service:
        name: "{{ (ansible_os_family == 'Debian') | ternary('ssh', 'sshd') }}"
        state: restarted
