#!/usr/bin/env bash
# Install Calypsi 65C816 toolchain as the output-quality benchmark.
# Self-contained: extract .deb payload into tools/calypsi rather than
# dpkg-install system-wide.

set -euo pipefail
source "$(dirname "$0")/common.sh"

CALYPSI_VERSION="5.16"
CALYPSI_DIR="$TOOLS_DIR/calypsi"
CALYPSI_DEB_URL="https://github.com/hth313/Calypsi-tool-chains/releases/download/${CALYPSI_VERSION}/calypsi-65816-${CALYPSI_VERSION}.deb"

if [ -x "$CALYPSI_DIR/usr/local/calypsi-65816/bin/cc65816" ] \
    || [ -x "$CALYPSI_DIR/opt/calypsi-65816/bin/cc65816" ] \
    || find "$CALYPSI_DIR" -maxdepth 6 -type f -name 'cc65816' 2>/dev/null | grep -q .; then
    log "calypsi already installed under $CALYPSI_DIR"
    exit 0
fi

deb="$(fetchCached "$CALYPSI_DEB_URL" "calypsi-65816-${CALYPSI_VERSION}.deb")"

log "extracting calypsi .deb payload"
install -d "$CALYPSI_DIR"
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
( cd "$tmp" && ar x "$deb" )

payload=""
for cand in data.tar.xz data.tar.zst data.tar.gz data.tar.bz2; do
    if [ -f "$tmp/$cand" ]; then
        payload="$tmp/$cand"
        break
    fi
done
[ -n "$payload" ] || die "could not find data.tar.* inside $deb"

tar -xf "$payload" -C "$CALYPSI_DIR"

# Locate the bin directory. Calypsi puts tools under /opt or /usr/local
# depending on package revision; find it and symlink into tools/calypsi/bin
# for a stable path.
ccBin="$(find "$CALYPSI_DIR" -maxdepth 6 -type f -name 'cc65816' -executable 2>/dev/null | head -1 || true)"
[ -n "$ccBin" ] || die "calypsi cc65816 not found after extract (inspect $CALYPSI_DIR)"
binDir="$(dirname "$ccBin")"
ln -sfn "$binDir" "$CALYPSI_DIR/bin"

log "calypsi install done"
log "  version:   $CALYPSI_VERSION"
log "  root:      $CALYPSI_DIR"
log "  binaries:  $CALYPSI_DIR/bin -> $binDir"
