#!/usr/bin/env bash
# Download and extract a vendored SDCC into third_party/sdcc-<VERSION>/.
# Idempotent: re-running with the same version is a no-op.

set -euo pipefail

VERSION="${1:-4.5.0}"

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

uname_s=$(uname -s)
uname_m=$(uname -m)

case "$uname_s" in
    Darwin)
        archive="sdcc-${VERSION}-x86_64-apple-macosx.tar.bz2"
        sf_dir="sdcc-macos-amd64"
        if [ "$uname_m" = "arm64" ]; then
            echo "Note: macOS binary is x86_64; on Apple Silicon it runs via Rosetta 2."
            if ! /usr/bin/arch -x86_64 /usr/bin/true 2>/dev/null; then
                echo
                echo "Rosetta 2 is not installed. Install it with:"
                echo "    softwareupdate --install-rosetta --agree-to-license"
                echo
                echo "Then re-run this script."
                exit 4
            fi
        fi
        ;;
    Linux)
        archive="sdcc-${VERSION}-amd64-unknown-linux2.5.tar.bz2"
        sf_dir="sdcc-linux-amd64"
        ;;
    *)
        echo "Unsupported host OS: $uname_s" >&2
        exit 2
        ;;
esac

dest="sdcc-${VERSION}"
if [ -d "$dest" ] && [ -x "$dest/bin/sdcc" ]; then
    echo "SDCC ${VERSION} already vendored at third_party/${dest}"
else
    url="https://sourceforge.net/projects/sdcc/files/${sf_dir}/${VERSION}/${archive}/download"
    if [ ! -f "$archive" ]; then
        echo "Downloading $archive..."
        curl -fL -o "$archive.tmp" "$url"
        mv "$archive.tmp" "$archive"
    else
        echo "Using cached $archive"
    fi
    echo "Extracting..."
    rm -rf "$dest"
    mkdir -p "$dest"
    tar -xjf "$archive" --strip-components 1 -C "$dest"
fi

ln -sfn "$dest" sdcc

echo
echo "Verifying installed toolchain:"
"$here/sdcc/bin/sdcc" --version 2>&1 | head -3 || {
    echo
    echo "Failed to run sdcc; if you saw 'Bad CPU type' run:"
    echo "    softwareupdate --install-rosetta --agree-to-license"
    exit 3
}

for tool in sdcc sdasz80 sdldz80 sdar sdobjcopy; do
    if [ -x "$here/sdcc/bin/$tool" ]; then
        echo "  found: bin/$tool"
    else
        echo "  MISSING: bin/$tool" >&2
    fi
done

echo
echo "Done. Toolchain at: third_party/sdcc -> $dest"
