#!/usr/bin/bash
# Diagnostic for 26.04 autoinstall failure during 'configure_apt'.
# Run from the live-installer shell:
#   curl -fsSL https://updates-dev.cavu.me/ubuntu/cdrom-keyring-debug.sh | sudo bash
set -u
hr() { echo; echo "============================================================"; echo "== $*"; echo "============================================================"; }

hr "1. subiquity traceback (top)"
cat /var/log/installer/subiquity-traceback.txt 2>/dev/null | head -20

hr "2. last 30 ERROR/FAIL lines from subiquity-server-debug.log"
grep -nE 'ERROR|FAIL:|exit status|NO_PUBKEY|Err:[0-9]| W: | E: ' /var/log/installer/subiquity-server-debug.log 2>/dev/null | tail -30

hr "3. apt stderr from inside curtin (full apt-get update output Subiquity logged)"
# Subiquity logs curtin's stderr to journald and into the server-debug log.
grep -nE 'apt-get update|W: |E: |GPG error|configure_apt' /var/log/installer/subiquity-server-debug.log 2>/dev/null | tail -40

hr "4. chroot dirs and their apt sources"
for TGT in /tmp/tmp*/mount; do
    [ -d "$TGT" ] || continue
    echo "------------------------------------"
    echo "TGT: $TGT"
    if [ -f "$TGT/etc/apt/sources.list" ]; then
        echo "--- $TGT/etc/apt/sources.list"
        cat "$TGT/etc/apt/sources.list"
    fi
    if [ -d "$TGT/etc/apt/sources.list.d" ]; then
        echo "--- ls $TGT/etc/apt/sources.list.d/"
        ls -la "$TGT/etc/apt/sources.list.d/"
        for f in "$TGT/etc/apt/sources.list.d/"*.{sources,list}; do
            [ -f "$f" ] || continue
            echo "--- $f"
            cat "$f"
        done
    fi
done

hr "5. live env: apt-get update — does the SAME source set work outside chroot?"
apt-get -o Debug::Acquire::gpgv=true update 2>&1 | tail -25

hr "6. each chroot: re-run apt-get update (no pty needed)"
for TGT in /tmp/tmp*/mount; do
    [ -d "$TGT" ] || continue
    [ -d "$TGT/usr/bin" ] || continue
    echo "------------------------------------"
    echo "TGT: $TGT"
    mount --bind /dev  "$TGT/dev"  2>/dev/null || true
    mount --bind /proc "$TGT/proc" 2>/dev/null || true
    mount --bind /sys  "$TGT/sys"  2>/dev/null || true
    cp -L /etc/resolv.conf "$TGT/etc/resolv.conf" 2>/dev/null || true
    # No outer sudo — we're already root; avoids pty alloc issue under curl|bash
    chroot "$TGT" /usr/bin/apt-get update 2>&1 | tail -30
done

hr "DONE"
