#!/usr/bin/env bash
# Run on the Proxmox host (root@10.130.60.224) to diagnose cloud-init build failures.
# Usage: scp this script to the host, then: bash troubleshoot-cloudinit-build.sh

set -e
echo "=== Cloud-init build troubleshoot ==="
echo ""

echo "1. xz available?"
if command -v xz >/dev/null 2>&1; then
    xz --version | head -1
else
    echo "   NOT FOUND. Install: apt install -y xz-utils"
fi
echo ""

echo "2. /tmp space (need several GB for decompress)?"
df -h /tmp
echo ""

echo "3. Provisioning dir and last request?"
PROV_DIR="${CM4_PROVISIONING_DIR:-/var/lib/cm4-provisioning}"
[[ -f /opt/cm4-provisioning/env ]] && source /opt/cm4-provisioning/env
echo "   PROV_DIR=$PROV_DIR"
if [[ -f "$PROV_DIR/build_cloudinit_request.json" ]]; then
    echo "   Last request URL: $(python3 -c "import json; print(json.load(open('$PROV_DIR/build_cloudinit_request.json')).get('url','?'))" 2>/dev/null || echo '?')"
else
    echo "   No request file (build may have already run)."
fi
echo ""

echo "4. Last build status?"
if [[ -f "$PROV_DIR/build_cloudinit_status.json" ]]; then
    cat "$PROV_DIR/build_cloudinit_status.json" | python3 -m json.tool 2>/dev/null || cat "$PROV_DIR/build_cloudinit_status.json"
else
    echo "   No status file."
fi
echo ""

TEST_DIR=$(mktemp -d)
trap "rm -rf $TEST_DIR" EXIT
echo "5. Quick xz decompress test?"
echo "test content" > "$TEST_DIR/f.txt"
xz -k "$TEST_DIR/f.txt" 2>/dev/null && xz -d -k -f "$TEST_DIR/f.txt.xz" 2>/dev/null && echo "   OK" || echo "   FAILED"
echo ""
echo "Done. If xz is missing, run on host: apt update && apt install -y xz-utils"
