#!/usr/bin/env bash
# syncpilot-bin ebuild updater for nbdy_overlay
# Checks GitHub releases for new versions
# Tag format: vX.Y.Z
# Every downloaded release asset is checked against the SHA256SUMS file that
# upstream publishes with the release before it enters the Manifest.

set -euo pipefail

CLEANUP_FILES=()
CLEANUP_DIRS=()
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
    if (( ${#CLEANUP_DIRS[@]} > 0 )); then
        for d in "${CLEANUP_DIRS[@]}"; do
            [[ -d "$d" ]] && rm -r "$d"
        done
    fi
}
trap cleanup_on_exit EXIT

OVERLAY_DIR="$(dirname "$(dirname "$(realpath "$0")")")"
EBUILD_DIR="${OVERLAY_DIR}/net-p2p/syncpilot-bin"
PKG_NAME="syncpilot-bin"
UPSTREAM_NAME="syncpilot"
GITHUB_REPO="turinglambdaai/syncpilot"

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 upstream version.
strip_rev() { sed 's/-r[0-9][0-9]*$//'; }

curl_github() {
    local curl_opts=(-sfL)
    [[ -n "${GITHUB_TOKEN:-}" ]] && curl_opts+=(-H "Authorization: Bearer ${GITHUB_TOKEN}")
    curl "${curl_opts[@]}" "$@"
}

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

get_latest_version() {
    local json version
    json=$(curl_github "https://api.github.com/repos/${GITHUB_REPO}/releases/latest" 2>/dev/null) || {
        log_error "Failed to fetch release info from GitHub"
        return 1
    }

    version=$(echo "$json" | grep -oP '"tag_name"\s*:\s*"v\K[0-9]+(\.[0-9]+)*(?=")' | head -1 || echo "")
    if [[ -z "$version" ]]; then
        log_error "Could not parse the version from GitHub releases"
        return 1
    fi
    echo "$version"
}

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_warn "Ebuild already exists: $new_ebuild"
        return 0
    fi

    cp "$old_ebuild" "$new_ebuild"
    CLEANUP_FILES+=("$new_ebuild")
    log_success "Created: ${PKG_NAME}-${new_version}.ebuild"
}

# Downloads URL into DEST, prints "SIZE BLAKE2B SHA512" and, when EXPECTED is a
# SHA256, fails if the file does not match it.
fetch_hashes() {
    local url="$1" dest="$2" expected="${3:-}"

    curl_github -o "$dest" "$url" || {
        log_error "Failed to download ${url}"
        return 1
    }

    if [[ -n "$expected" ]]; then
        local actual
        actual=$(sha256sum "$dest" | awk '{print $1}')
        if [[ "$actual" != "$expected" ]]; then
            log_error "SHA256 mismatch for ${url##*/}: expected ${expected}, got ${actual}"
            return 1
        fi
    fi

    echo "$(wc -c < "$dest") $(b2sum "$dest" | awk '{print $1}') $(sha512sum "$dest" | awk '{print $1}')"
}

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

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

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

    pv=$(basename "$ebuild" .ebuild | sed "s/${PKG_NAME}-//" | strip_rev)
    base="https://github.com/${GITHUB_REPO}"
    tmpdir=$(mktemp -d)
    CLEANUP_DIRS+=("$tmpdir")

    local sums="${tmpdir}/SHA256SUMS"
    curl_github -o "$sums" "${base}/releases/download/v${pv}/SHA256SUMS" || {
        log_error "Failed to download SHA256SUMS for v${pv}"
        return 1
    }

    # distfile name : source URL : name in SHA256SUMS ("-" when unpublished).
    # The tag archive and the tag icon are not part of the release assets, so
    # they have no published checksum.
    local -a entries=(
        "${UPSTREAM_NAME}-${pv}-linux-x64.tar.gz|${base}/releases/download/v${pv}/${UPSTREAM_NAME}-${pv}-linux-x64.tar.gz|${UPSTREAM_NAME}-${pv}-linux-x64.tar.gz"
        "${UPSTREAM_NAME}-${pv}-linux-arm64.tar.gz|${base}/releases/download/v${pv}/${UPSTREAM_NAME}-${pv}-linux-arm64.tar.gz|${UPSTREAM_NAME}-${pv}-linux-arm64.tar.gz"
        "${PKG_NAME}-${pv}-src.tar.gz|${base}/archive/refs/tags/v${pv}.tar.gz|-"
        "${PKG_NAME}-${pv}-icon-512.png|${base}/raw/v${pv}/assets/icon-512.png|-"
    )

    local lines="" entry distfile url sumname expected hashes
    for entry in "${entries[@]}"; do
        IFS='|' read -r distfile url sumname <<< "$entry"
        expected=""
        if [[ "$sumname" != "-" ]]; then
            expected=$(awk -v n="$sumname" '$2 == n {print $1}' "$sums")
            if [[ -z "$expected" ]]; then
                log_error "${sumname} is not listed in SHA256SUMS"
                return 1
            fi
        fi
        log_info "Downloading ${distfile}..."
        hashes=$(fetch_hashes "$url" "${tmpdir}/${distfile}" "$expected") || return 1
        read -r size b2 s512 <<< "$hashes"
        [[ -n "$expected" ]] && log_success "SHA256 verified: ${sumname}"
        lines+="DIST ${distfile} ${size} BLAKE2B ${b2} SHA512 ${s512}"$'\n'
    done

    printf '%s' "$lines" | LC_ALL=C sort > "${EBUILD_DIR}/Manifest"
    log_success "Manifest generated for ${pv}"
}

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="net-p2p/${PKG_NAME}: 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 ;;
            --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)"
                echo "Set GITHUB_TOKEN to raise the GitHub API rate limit."
                exit 0
                ;;
            *) log_error "Unknown option: $1"; exit 1 ;;
        esac
    done

    echo "============================================"
    echo "  SyncPilot 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"

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

    log_success "Update complete: ${latest_version}"
}

main "$@"
