#!/bin/bash -e

# Pre-chroot script: Source a pre-built PM3 tarball for installation.
# This runs on the host before the chroot script.
#
# Tarball sources (checked in order):
#   1. PM3_TARBALL env var (explicit path to a local tarball)
#   2. Local file in this substage's files/ directory
#   3. Download from GitHub Releases (dangerous-tacos/dangerous-pi)

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

# --- Detect Python ABI in chroot ---
PYTHON_VERSION=$(chroot "${ROOTFS_DIR}" python3 -c \
    'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")' 2>/dev/null || echo "3.12")
PYTHON_ABI="cp$(echo "$PYTHON_VERSION" | tr -d '.')"
echo "Detected Python ${PYTHON_VERSION} (ABI: ${PYTHON_ABI}) in chroot"

# --- Read PM3 version config ---
PM3_COMMIT=""
if [ -f "${SCRIPT_DIR}/pm3-version.conf" ]; then
    . "${SCRIPT_DIR}/pm3-version.conf"
fi

# --- Locate tarball ---
TARBALL=""

# 1. Explicit env var
if [ -n "${PM3_TARBALL:-}" ] && [ -f "$PM3_TARBALL" ]; then
    echo "Using PM3 tarball from PM3_TARBALL: $PM3_TARBALL"
    TARBALL="$PM3_TARBALL"
fi

# 2. Local file in files/ directory
if [ -z "$TARBALL" ]; then
    LOCAL_MATCH=$(ls "${SCRIPT_DIR}"/files/pm3-*-aarch64-linux-${PYTHON_ABI}.tar.gz 2>/dev/null | head -1)
    if [ -n "$LOCAL_MATCH" ]; then
        echo "Using local PM3 tarball: $LOCAL_MATCH"
        TARBALL="$LOCAL_MATCH"
    fi
fi

# 3. Download from GitHub Releases
if [ -z "$TARBALL" ]; then
    GH_REPO="dangerous-tacos/dangerous-pi"
    echo "Downloading PM3 tarball from GitHub Releases (${GH_REPO})..."

    # Determine which release to fetch
    if [ -n "$PM3_COMMIT" ]; then
        # Try to find a release matching the commit
        RELEASE_URL="https://api.github.com/repos/${GH_REPO}/releases/latest"
    else
        RELEASE_URL="https://api.github.com/repos/${GH_REPO}/releases/latest"
    fi

    # Get asset download URL for the matching ABI
    ASSET_PATTERN="pm3-.*-aarch64-linux-${PYTHON_ABI}\\.tar\\.gz"
    DOWNLOAD_URL=$(curl -sL "$RELEASE_URL" | \
        grep -oP "\"browser_download_url\":\\s*\"\\K[^\"]*${ASSET_PATTERN}" | head -1)

    if [ -n "$DOWNLOAD_URL" ]; then
        TARBALL="/tmp/pm3-prebuilt-download.tar.gz"
        echo "Downloading: $DOWNLOAD_URL"
        curl -sL -o "$TARBALL" "$DOWNLOAD_URL"
        echo "Downloaded PM3 tarball ($(du -h "$TARBALL" | cut -f1))"
    else
        echo "WARNING: Could not find PM3 tarball for ABI ${PYTHON_ABI} in latest release"
        echo "Falling back to compile-from-source (this will take 45-60 min under QEMU)"
        echo "To avoid this, set PM3_TARBALL=/path/to/pm3-*.tar.gz"

        # Copy patches and version config for the compile fallback
        if [ -f "${SCRIPT_DIR}/led-pwm-control.patch" ]; then
            cp "${SCRIPT_DIR}/led-pwm-control.patch" "${ROOTFS_DIR}/tmp/"
        fi
        if [ -f "${SCRIPT_DIR}/hf-booster-detection.patch" ]; then
            cp "${SCRIPT_DIR}/hf-booster-detection.patch" "${ROOTFS_DIR}/tmp/"
        fi
        if [ -f "${SCRIPT_DIR}/pm3-version.conf" ]; then
            cp "${SCRIPT_DIR}/pm3-version.conf" "${ROOTFS_DIR}/tmp/"
        fi
        touch "${ROOTFS_DIR}/tmp/PM3_COMPILE_FROM_SOURCE"
        exit 0
    fi
fi

# --- Copy tarball into rootfs ---
cp "$TARBALL" "${ROOTFS_DIR}/tmp/pm3-prebuilt.tar.gz"
echo "PM3 tarball staged at /tmp/pm3-prebuilt.tar.gz in rootfs"

# Clean up downloaded temp file
if [ "${TARBALL}" = "/tmp/pm3-prebuilt-download.tar.gz" ]; then
    rm -f "$TARBALL"
fi
