---
- name: Fix dpkg and initramfs issues on hcs
  hosts: hcs
  become: yes
  tasks:
    - name: Check current dpkg status
      shell: dpkg --audit
      register: dpkg_status
      ignore_errors: yes

    - name: Display dpkg status
      debug:
        var: dpkg_status.stdout_lines

    - name: Fix broken btrfs hook
      shell: |
        # Remove problematic btrfs hook temporarily
        mv /usr/share/initramfs-tools/hooks/btrfs /usr/share/initramfs-tools/hooks/btrfs.bak || true
        
        # Try to reconfigure the failed package
        dpkg --configure -a
        
        # If that works, restore the hook
        if [ $? -eq 0 ]; then
          mv /usr/share/initramfs-tools/hooks/btrfs.bak /usr/share/initramfs-tools/hooks/btrfs || true
        fi
      register: fix_result
      ignore_errors: yes

    - name: Display fix result
      debug:
        var: fix_result

    - name: Alternative fix - reinstall initramfs-tools
      apt:
        name: initramfs-tools
        state: latest
        force: yes
      when: fix_result.rc != 0
      ignore_errors: yes

    - name: Clean up and update
      shell: |
        apt autoremove -y
        apt update
        apt upgrade -y
      ignore_errors: yes

    - name: Check final dpkg status
      shell: dpkg --audit
      register: final_status
      ignore_errors: yes

    - name: Display final status
      debug:
        var: final_status.stdout_lines