#!/bin/sh
set -eu

if ! command -v bb >/dev/null 2>&1; then
  echo "kotobase requires Babashka: https://babashka.org" >&2
  exit 1
fi
if ! command -v curl >/dev/null 2>&1; then
  echo "kotobase installer requires curl" >&2
  exit 1
fi

data_root=${XDG_DATA_HOME:-"$HOME/.local/share"}
bin_root=${KOTOBASE_BIN_DIR:-"$HOME/.local/bin"}
install_root=${KOTOBASE_INSTALL_DIR:-"$data_root/kotobase"}

mkdir -p "$install_root" "$bin_root"
curl -fsSL https://kotobase.net/cli/kotobase-v2.clj -o "$install_root/kotobase.clj"

launcher="$bin_root/kotobase"
{
  printf '%s\n' '#!/bin/sh' 'set -eu'
  printf 'exec bb %s "$@"\n' \
    "$(printf %s "$install_root/kotobase.clj" | sed "s/'/'\\\\''/g; s/.*/'&'/")"
} > "$launcher"
chmod 0755 "$launcher"

echo "installed kotobase CLI: $launcher"
case ":$PATH:" in
  *":$bin_root:"*) "$launcher" help ;;
  *) echo "add $bin_root to PATH, then run: kotobase help" ;;
esac
