#!/usr/bin/env bash
# installCadius.sh - clone, build, and install the Brutal Deluxe cadius
# ProDOS-disk tool into tools/cadius/cadius.  Demo + runViaFinder
# scripts default to this location.
#
# Usage: bash scripts/installCadius.sh
# Idempotent: skips clone if source dir already present; skips build
# if the binary is already in place.

set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
SRC_DIR="$PROJECT_ROOT/tools/cadius-src"
DEST_DIR="$PROJECT_ROOT/tools/cadius"
DEST_BIN="$DEST_DIR/cadius"

if [ -x "$DEST_BIN" ]; then
    echo "cadius already installed at $DEST_BIN"
    exit 0
fi

mkdir -p "$DEST_DIR"

if [ ! -d "$SRC_DIR/.git" ]; then
    rm -rf "$SRC_DIR"
    git clone --depth 1 https://github.com/mach-kernel/cadius "$SRC_DIR"
fi

(cd "$SRC_DIR" && make)

cp "$SRC_DIR/bin/release/cadius" "$DEST_BIN"
chmod +x "$DEST_BIN"
echo "installed: $DEST_BIN"
"$DEST_BIN" 2>&1 | head -1
