#!/usr/bin/env sh

### This script has a two simple responibilites:
### 1. Ensure a proper Python environment is available (Python 3.12+)
### 2. Run the actual bootstrap.py script using that Python environment
###
### The Python virtual environment is unique to xSensrKernel and should be present at
### $HOME/.local/share/xSensrKernel/tools/python/venv
### The uv tool is used to to download and install Python,
### and the uv-managed Python is used to create the virtual environment.
### uv is utilised ephemerally during the bootstrap process and is not a long-term dependency of xSensrKernel.

set -eu

BOOTSTRAP_VERSION="1"

APPDIR="$HOME/.local/share/xSensrKernel"

UVCMD=""
UVDIR="$APPDIR/tools/uv"
UVEXE="$UVDIR/uv"
PYTHONDIR="$APPDIR/tools/python"
PYTHON_BINDIR="$PYTHONDIR/bin"
VENV_DIR="$PYTHONDIR/venv"
PYTHON="$VENV_DIR/bin/python"
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)

run() {
    ensure_python

    write_log "Found xSensrKernel Python: ${PYTHON}"
    # Ensure resolved python also has pip
    if ! ${PYTHON} -m pip --version >/dev/null 2>&1; then
        write_fail "pip not found for xSensrKernel Python"
        exit 1
    fi
    write_log "Found pip for xSensrKernel Python"

    ensure_bootstrap_script

    write_log "Running bootstrap.py using xSensrKernel Python"
    if [ -r /dev/tty ]; then
        # Force bootstrap.py stdin to come from the controlling terminal so
        # Python input() prompts remain interactive even if this script's stdin
        # is redirected/piped.
        "$PYTHON" "$SCRIPT_DIR/bootstrap.py" </dev/tty
    else
        write_fail "No controlling TTY available for interactive bootstrap prompts."
        write_fail "Run bootstrap.sh from an interactive terminal."
        exit 1
    fi
    # Placeholder for the actual update logic that uses $PYTHON
    # e.g., $PYTHON build_deb.py --output "${DEB_PATH}"
}

write_log() {
    echo "[bootstrap linux] $1"
}

write_fail() {
    echo "[bootstrap linux] ERROR: $1" >&2
}

ensure_bootstrap_script() {
    if test_bootstrap_script; then
        return 0
    fi

    write_log "bootstrap.py not found. Attempting to download..."
    download_bootstrap_script

    if ! test_bootstrap_script; then
        write_fail "bootstrap.py not found after download attempt."
        write_fail "You might be using an outdated version of bootstrap.sh."
        exit 1
    fi
}

test_bootstrap_script() {
    # Check if bootstrap.py exists in the script directory
    # if it exists, check that BOOTSTRAP_VERSION matches the expected version
    if [ -f "$SCRIPT_DIR/bootstrap.py" ]; then
        version_line=$(grep -E '^BOOTSTRAP_VERSION\s*=\s*["'"'"']([0-9]+)["'"'"']' "$SCRIPT_DIR/bootstrap.py" | head -n 1 || true)
        if [ -n "$version_line" ]; then
            version=$(printf '%s' "$version_line" | tr -d '\r' | sed -E 's/^BOOTSTRAP_VERSION\s*=\s*["'"'"']([0-9]+)["'"'"'].*/\1/' | tr -d '[:space:]')
            if [ "$version" = "$BOOTSTRAP_VERSION" ]; then
                return 0
            else
                write_log "bootstrap.py version mismatch: expected $BOOTSTRAP_VERSION, found $version"
                return 1
            fi
        else
            write_log "bootstrap.py does not contain a BOOTSTRAP_VERSION declaration"
            return 1
        fi
    fi
    return 1
}

download_bootstrap_script() {
    write_log "Downloading bootstrap.py to '$SCRIPT_DIR/bootstrap.py'..."

    BOOTSTRAP_URL="https://kernel.xsensr.com/bootstrap.py"
    BOOTSTRAP_UA="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"

    if ! command -v curl >/dev/null 2>&1 && ! command -v wget >/dev/null 2>&1; then
        write_fail "Neither curl nor wget is available. Cannot download bootstrap.py automatically."
        exit 1
    fi

    if command -v curl >/dev/null 2>&1; then
        if curl -fLsS --retry 2 --retry-delay 1 --retry-all-errors --http1.1 \
            -A "$BOOTSTRAP_UA" \
            -H "Accept: application/octet-stream,*/*" \
            -H "Referer: https://kernel.xsensr.com" \
            -o "$SCRIPT_DIR/bootstrap.py" "$BOOTSTRAP_URL"; then
            return 0
        fi

        # Some edges reject explicit browser UA/header combinations; retry with curl defaults.
        if curl -fLsS --retry 2 --retry-delay 1 --retry-all-errors --http1.1 \
            -o "$SCRIPT_DIR/bootstrap.py" "$BOOTSTRAP_URL"; then
            return 0
        fi
    else
        if wget -qO "$SCRIPT_DIR/bootstrap.py" \
            --user-agent="$BOOTSTRAP_UA" \
            --header="Accept: application/octet-stream,*/*" \
            --header="Referer: https://kernel.xsensr.com" \
            "$BOOTSTRAP_URL"; then
            return 0
        fi

        if wget -qO "$SCRIPT_DIR/bootstrap.py" "$BOOTSTRAP_URL"; then
            return 0
        fi
    fi

    rm -f "$SCRIPT_DIR/bootstrap.py" 2>/dev/null || true
    write_fail "Failed to download bootstrap.py from $BOOTSTRAP_URL."
    write_fail "If this persists, download manually from https://kernel.xsensr.com/bootstrap.py"
    exit 1
}

ensure_uv() {
    if check_uv; then
        return 0
    fi

    write_log "uv not found. Attempting to install uv..."
    install_uv

    if ! check_uv; then
        write_fail "uv not found after installation attempt."
        write_fail "Install uv manually: https://docs.astral.sh/uv/getting-started/installation/"
        exit 1
    fi
}

check_uv() {
    if [ -x "$UVEXE" ]; then
        UVCMD="$UVEXE"
        return 0
    fi

    if command -v uv >/dev/null 2>&1; then
        UVCMD="uv"
        return 0
    fi

    return 1
}

install_uv() {
    export UV_UNMANAGED_INSTALL=1
    export UV_INSTALL_DIR="$UVDIR"

    if command -v curl >/dev/null 2>&1; then
        curl -LsSf https://astral.sh/uv/install.sh | sh
    elif command -v wget >/dev/null 2>&1; then
        wget -qO- https://astral.sh/uv/install.sh | sh
    else
        write_fail "Neither curl nor wget is available. Cannot install uv automatically."
        write_fail "To install either wget or curl, use your package manager. For example:"
        if command -v sudo >/dev/null 2>&1; then
            write_fail "   On Debian/Ubuntu: sudo apt-get install wget"
            write_fail "   On Fedora: sudo dnf install wget"
            write_fail "   On Arch: sudo pacman -S wget"
        else # If sudo is not available, just provide instructions without it
            write_fail "as root or with appropriate permissions:"
            write_fail "   On Debian/Ubuntu: apt-get install wget"
            write_fail "   On Fedora: dnf install wget"
            write_fail "   On Arch: pacman -S wget"
        fi
        write_fail "After installing curl or wget, please rerun this script."
        exit 1
    fi
}

ensure_python() {
    if check_python; then
        return 0
    fi

    write_log "Python not found. Attempting to install..."
    install_python

    if ! check_python; then
        write_fail "Python not found after installation attempt. Please install Python 3.12+ manually and rerun this script."
        exit 1
    fi
}

check_python() {
    if [ -x "$PYTHON" ] && "$PYTHON" --version >/dev/null 2>&1; then
        return 0
    fi
    return 1
}

install_python() {
    ensure_uv

    write_log "Installing Python 3.12 via uv..."
    "$UVCMD" python install --no-bin --no-cache --install-dir "$PYTHON_BINDIR" 3.12

    export UV_PYTHON_INSTALL_DIR="$PYTHON_BINDIR"

    write_log "Creating bootstrap virtual environment: $VENV_DIR"
    mkdir -p "$PYTHONDIR"
    "$UVCMD" venv --no-cache --python 3.12 --seed --clear "$VENV_DIR"
}

run