---
# Исправление источников apt на хостах Debian, у которых ещё остались репозитории Bullseye (Debian 11).
# Заменяет bullseye → bookworm в /etc/apt/sources.list и удаляет сломанные
# сторонние репозитории, у которых больше нет валидных Release-файлов или GPG-ключей.
#
# Запуск (сначала dry-run):
#   ansible-playbook -i inventory/prod playbooks/fix_apt_sources.yml --check
# Запуск:
#   ansible-playbook -i inventory/prod playbooks/fix_apt_sources.yml
# Ограничить конкретными хостами:
#   ansible-playbook -i inventory/prod playbooks/fix_apt_sources.yml --limit zabbix,netxms,svc-node-3
- name: Fix apt sources — upgrade Bullseye repos to Bookworm
  hosts: debian
  gather_facts: false
  become: true

  tasks:
    - name: Check current codename in /etc/apt/sources.list
      ansible.builtin.command: grep -c bullseye /etc/apt/sources.list
      register: bullseye_check
      changed_when: false
      failed_when: bullseye_check.rc not in [0, 1]

    - name: Replace bullseye with bookworm in /etc/apt/sources.list
      ansible.builtin.replace:
        path: /etc/apt/sources.list
        regexp: \bbullseye\b
        replace: bookworm
      when: bullseye_check.rc == 0 and bullseye_check.stdout | int > 0
      notify: Update apt cache

    - name: Find third-party apt sources with bullseye codename
      ansible.builtin.find:
        paths: /etc/apt/sources.list.d
        patterns: "*.list"
        contains: bullseye
      register: broken_sources

    - name: Show third-party sources that reference bullseye
      ansible.builtin.debug:
        msg: "Found broken source file: {{ item.path }}"
      loop: "{{ broken_sources.files }}"
      loop_control:
        label: "{{ item.path }}"

    - name: Disable broken third-party bullseye repos (rename to .disabled)
      ansible.builtin.command: mv {{ item.path }} {{ item.path }}.disabled
      args:
        removes: "{{ item.path }}"
      loop: "{{ broken_sources.files }}"
      loop_control:
        label: "{{ item.path }}"
      notify: Update apt cache

  handlers:
    - name: Update apt cache
      ansible.builtin.apt:
        update_cache: true
