---
- name: Fix master node - rename to ch4 and restore SSH port 22
  hosts: master
  become: yes
  vars:
    new_hostname: ch4
    old_hostname: master
  
  tasks:
    - name: Backup current hostname
      copy:
        content: "{{ old_hostname }}"
        dest: /etc/hostname.backup
        mode: '0644'
      when: ansible_hostname == old_hostname

    - name: Update hostname to ch4
      hostname:
        name: "{{ new_hostname }}"
      when: ansible_hostname == old_hostname

    - name: Update /etc/hostname file
      copy:
        content: "{{ new_hostname }}"
        dest: /etc/hostname
        mode: '0644'
      when: ansible_hostname == old_hostname

    - name: Update /etc/hosts file
      lineinfile:
        path: /etc/hosts
        regexp: '^127\.0\.1\.1.*{{ old_hostname }}'
        line: '127.0.1.1 {{ new_hostname }}'
        state: present
      when: ansible_hostname == old_hostname

    - name: Update Tailscale hostname
      shell: |
        tailscale set --hostname={{ new_hostname }}
      when: ansible_hostname == old_hostname

    - name: Backup SSH config
      copy:
        src: /etc/ssh/sshd_config
        dest: /etc/ssh/sshd_config.backup
        remote_src: yes
        backup: yes

    - name: Restore SSH port to 22
      lineinfile:
        path: /etc/ssh/sshd_config
        regexp: '^Port '
        line: 'Port 22'
        state: present

    - name: Restart SSH service
      systemd:
        name: ssh
        state: restarted
        enabled: yes

    - name: Wait for SSH to be ready on port 22
      wait_for:
        port: 22
        host: "{{ ansible_default_ipv4.address }}"
        delay: 5
        timeout: 30

    - name: Test SSH connection on port 22
      ping:
      delegate_to: "{{ inventory_hostname }}"
      vars:
        ansible_port: 22

    - name: Display completion message
      debug:
        msg: |
          ✅ Successfully renamed {{ old_hostname }} to {{ new_hostname }}
          ✅ SSH port restored to 22
          ✅ Tailscale hostname updated
          🔄 Please update your inventory file to use the new hostname and port

