#!/usr/bin/bash
set -euo pipefail

# OpenCode 2 loads plugins from directories, not from single files.
# We install a real plugin directory containing a small entry point that
# re-exports the implementation from /opt/plagin-tokens.
SOURCE_DIR="${PLAGIN_TOKENS_SOURCE:-/opt/plagin-tokens}"
PLUGINS_DIR="${PLAGIN_TOKENS_PLUGINS_DIR:-$HOME/.config/opencode/plugins}"
TARGET_DIR="$PLUGINS_DIR/plagin-tokens"
LEGACY_FILE="$PLUGINS_DIR/plagin-tokens.ts"

if [[ ! -f "$SOURCE_DIR/index.ts" ]]; then
  echo "plagin-tokens source not found at $SOURCE_DIR" >&2
  exit 1
fi

mkdir -p "$TARGET_DIR"

cat > "$TARGET_DIR/index.ts" <<EOF
// Generated by plagin-tokens-install. Do not edit.
export { default } from "$SOURCE_DIR/index.ts"
EOF

# OpenCode 1 installs linked a single .ts file; OpenCode 2 skips those.
if [[ -e "$LEGACY_FILE" || -L "$LEGACY_FILE" ]]; then
  rm -f "$LEGACY_FILE"
  echo "Removed legacy file plugin: $LEGACY_FILE"
fi

echo "Installed opencode plugin directory: $TARGET_DIR"
echo "Restart opencode to load it."
