#!/bin/bash
# check-repos-and-reboot.sh - checks reboot-required + Proxmox repo config on all hosts.
set -uo pipefail
SSH_OPTS=(-o BatchMode=yes -o ConnectTimeout=8 -o StrictHostKeyChecking=accept-new)
HOSTS=(pfv-tsys1 pfv-tsys3 pfv-tsys4 pfv-tsys5 pfv-tsys6 pfv-tsys7)

for host in "${HOSTS[@]}"; do
    echo "================================================================"
    echo "[$host]"
    echo "================================================================"

    if ! ssh "${SSH_OPTS[@]}" "root@$host" 'echo ok' >/dev/null 2>&1; then
        echo "  UNREACHABLE"
        continue
    fi

    echo "--- /var/run/reboot-required ---"
    ssh "${SSH_OPTS[@]}" "root@$host" 'if [ -r /var/run/reboot-required ]; then echo "REBOOT REQUIRED"; cat /var/run/reboot-required 2>/dev/null; if [ -r /var/run/reboot-required.pkgs ]; then echo "Packages triggering:"; cat /var/run/reboot-required.pkgs; fi; else echo "(no reboot required marker)"; fi'

    echo ""
    echo "--- Running kernel vs installed kernel ---"
    ssh "${SSH_OPTS[@]}" "root@$host" 'echo "running: $(uname -r)"; echo "installed:"; dpkg -l | grep -E "pve-kernel-[0-9]" | awk "{print \"  \"\$2\"  \"\$3}" | tail -5'

    echo ""
    echo "--- Proxmox repositories (apt sources) ---"
    ssh "${SSH_OPTS[@]}" "root@$host" 'grep -rh "pve\|proxmox" /etc/apt/sources.list /etc/apt/sources.list.d/ 2>/dev/null | grep -v "^#" | sed "s/^/  /"'

    echo ""
    echo "--- Enterprise repo status (should be commented or absent if no subscription) ---"
    ssh "${SSH_OPTS[@]}" "root@$host" 'grep -l "pve-enterprise" /etc/apt/sources.list /etc/apt/sources.list.d/* 2>/dev/null | while read f; do echo "  File: $f"; grep -n "pve-enterprise" "$f" | sed "s/^/    /"; done'

    echo ""
    echo "--- no-subscription repo presence ---"
    ssh "${SSH_OPTS[@]}" "root@$host" 'grep -rl "pve-no-subscription" /etc/apt/sources.list /etc/apt/sources.list.d/ 2>/dev/null | while read f; do echo "  File: $f"; grep -n "pve-no-subscription" "$f" | sed "s/^/    /"; done'

    echo ""
    echo "--- Recently updated packages (last 24h, kernel-related) ---"
    ssh "${SSH_OPTS[@]}" "root@$host" 'grep -E "pve-kernel|proxmox|pve-qemu|zfs" /var/log/dpkg.log 2>/dev/null | grep "$(date +%Y-%m-%d)\|$(date -d yesterday +%Y-%m-%d)" | tail -15 || echo "(none in dpkg.log)"'

    echo ""
done
