#!/usr/bin/env bash
# LM Studio ebuild updater for nbdy_overlay
# Follows the redirect of the official "latest" Linux .deb download.
# Upstream "0.4.24-1" maps to PV "0.4.24.1" (build number as 4th component).

set -euo pipefail

# Cleanup on failure: remove any newly created ebuild
CLEANUP_FILES=()
cleanup_on_exit() {
    local exit_code=$?
    if (( exit_code != 0 )) && (( ${#CLEANUP_FILES[@]} > 0 )); then
        for f in "${CLEANUP_FILES[@]}"; do
            [[ -f "$f" ]] && rm -v "$f"
        done
    fi
}
trap cleanup_on_exit EXIT

OVERLAY_DIR="$(dirname "$(dirname "$(realpath "$0")")")"
EBUILD_DIR="${OVERLAY_DIR}/app-misc/lmstudio-bin"
PKG_NAME="lmstudio-bin"
LATEST_URL="https://lmstudio.ai/download/latest/linux/x64?format=deb"
INSTALLERS_BASE="https://installers.lmstudio.ai/linux/x64"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[OK]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1" >&2; }

# Strip a Gentoo revision suffix (-rN) to recover the version mapped from upstream.
strip_rev() { sed 's/-r[0-9][0-9]*$//'; }

# 0.4.24.1 -> 0.4.24-1
pv_to_upstream() { sed -E 's/\.([0-9]+)$/-\1/'; }

get_current_version() {
    local ebuild
    ebuild=$(ls "${EBUILD_DIR}"/*.ebuild 2>/dev/null | sort -V | tail -1)
    if [[ -z "$ebuild" ]]; then
        echo ""
        return
    fi
    basename "$ebuild" .ebuild | sed "s/${PKG_NAME}-//" | strip_rev
}

# The "latest" endpoint answers with a 302 to the versioned installer URL:
# https://installers.lmstudio.ai/linux/x64/0.4.24-1/LM-Studio-0.4.24-1-x64.deb
get_latest_version() {
    local location
    location=$(curl -sfI "$LATEST_URL" 2>/dev/null | tr -d '\r' | grep -i '^location:' | tail -1) || {
        log_error "Failed to query $LATEST_URL"
        return 1
    }

    local upstream
    upstream=$(echo "$location" | grep -oP '/linux/x64/\K[0-9]+(\.[0-9]+)*-[0-9]+(?=/)' || echo "")

    if [[ -z "$upstream" ]]; then
        log_error "Could not parse version from redirect: ${location:-<none>}"
        return 1
    fi

    echo "${upstream%-*}.${upstream##*-}"
}

create_ebuild() {
    local new_version="$1"
    local old_ebuild new_ebuild

    old_ebuild=$(ls "${EBUILD_DIR}"/*.ebuild 2>/dev/null | sort -V | tail -1)
    new_ebuild="${EBUILD_DIR}/${PKG_NAME}-${new_version}.ebuild"

    if [[ -z "$old_ebuild" ]]; then
        log_error "No existing ebuild found to copy"
        return 1
    fi

    if [[ -f "$new_ebuild" ]]; then
        log_info "Ebuild ${PKG_NAME}-${new_version}.ebuild already exists"
        return 0
    fi

    # Version is derived from the filename, no content changes needed
    cp "$old_ebuild" "$new_ebuild"
    CLEANUP_FILES+=("$new_ebuild")
    log_success "Created: ${PKG_NAME}-${new_version}.ebuild"
}

generate_manifest() {
    log_info "Generating Manifest..."

    local ebuild
    ebuild=$(ls "${EBUILD_DIR}"/*.ebuild 2>/dev/null | sort -V | tail -1)

    if [[ -z "$ebuild" ]]; then
        log_error "No ebuild found"
        return 1
    fi

    local pv upstream src_url distfile
    pv=$(basename "$ebuild" .ebuild | sed "s/${PKG_NAME}-//" | strip_rev)
    upstream=$(echo "$pv" | pv_to_upstream)
    src_url="${INSTALLERS_BASE}/${upstream}/LM-Studio-${upstream}-x64.deb"
    # Matches the SRC_URI '-> ${P}.deb' rename
    distfile="${PKG_NAME}-${pv}.deb"

    log_info "Downloading ${distfile} for checksum (~800 MB)..."
    local tmpfile
    tmpfile=$(mktemp)

    if ! curl -sfL -o "$tmpfile" "$src_url"; then
        log_error "Failed to download ${src_url}"
        rm -f "$tmpfile"
        return 1
    fi

    local filesize blake2b sha512
    filesize=$(wc -c < "$tmpfile")
    blake2b=$(b2sum "$tmpfile" | awk '{print $1}')
    sha512=$(sha512sum "$tmpfile" | awk '{print $1}')
    rm -f "$tmpfile"

    echo "DIST ${distfile} ${filesize} BLAKE2B ${blake2b} SHA512 ${sha512}" > "${EBUILD_DIR}/Manifest"
    log_success "Manifest generated for ${distfile} (${filesize} bytes)"
}

cleanup_old_versions() {
    local keep="${1:-1}"
    local ebuilds

    mapfile -t ebuilds < <(ls "${EBUILD_DIR}"/*.ebuild 2>/dev/null | sort -V)
    local count=${#ebuilds[@]}

    if (( count <= keep )); then
        log_info "No cleanup needed (${count} versions, keeping ${keep})"
        return
    fi

    local to_remove=$((count - keep))
    log_info "Removing ${to_remove} old version(s)..."

    for ((i = 0; i < to_remove; i++)); do
        rm -v "${ebuilds[$i]}"
    done

    log_success "Cleanup complete"
}

git_commit() {
    local version="$1"

    cd "${OVERLAY_DIR}"
    git add "${EBUILD_DIR}/"

    if git diff --cached --quiet; then
        log_info "No changes to commit"
        return 0
    fi

    local msg="app-misc/lmstudio-bin: bump to ${version}"
    git commit -m "$msg"
    log_success "Committed: $msg"
}

main() {
    local dry_run=false
    local force=false
    local no_commit=false
    local keep_versions=1

    while [[ $# -gt 0 ]]; do
        case $1 in
            -n|--dry-run) dry_run=true; shift ;;
            -f|--force) force=true; shift ;;
            --no-commit) no_commit=true; shift ;;
            --no-push) no_commit=true; shift ;;
            --keep) keep_versions="$2"; shift 2 ;;
            -h|--help)
                echo "Usage: $0 [OPTIONS]"
                echo "  -n, --dry-run    Preview changes"
                echo "  -f, --force      Force update"
                echo "  --no-commit      Don't git commit"
                echo "  --keep N         Keep N old versions (default: 1)"
                exit 0
                ;;
            *) log_error "Unknown option: $1"; exit 1 ;;
        esac
    done

    echo "============================================"
    echo "  LM Studio Ebuild Updater"
    echo "============================================"
    echo ""

    local current_version latest_version
    current_version=$(get_current_version)
    latest_version=$(get_latest_version) || exit 1

    echo "Current: ${current_version:-<none>}"
    echo "Latest:  ${latest_version}"
    echo ""

    if [[ "$current_version" == "$latest_version" ]] && [[ "$force" != "true" ]]; then
        log_success "Already up to date!"
        exit 0
    fi

    if [[ "$dry_run" == "true" ]]; then
        log_info "[DRY-RUN] Would update to ${latest_version}"
        exit 0
    fi

    create_ebuild "$latest_version"
    generate_manifest
    cleanup_old_versions "$keep_versions"

    # Clear cleanup list on success (files are committed, not orphans)
    CLEANUP_FILES=()

    if [[ "$no_commit" != "true" ]]; then
        git_commit "$latest_version"
    fi

    log_success "Update complete: ${latest_version}"
}

main "$@"
