#!/usr/bin/env bash
# claude-code-clip — installer for the /clip skill + the `clip` CLI.
#
#   curl -fsSL https://jinhuang712.github.io/claude-code-clip/install.sh | bash
#
# Installs into ~/.claude/skills/clip/ — that folder name (clip) is what
# registers the bare /clip command. It ships as a standalone skill, NOT a
# plugin, on purpose: a plugin would always namespace the command as
# /clip:clip. Same reasoning as claude-code-queue; see that repo's CLAUDE.md.
#
# Also symlinks the CLI to ~/.local/bin/clip so `clip <path>` works in any
# terminal. Both halves are the same script — one capability, two front doors.
#
# Re-running updates in place. To uninstall:
#   rm -rf ~/.claude/skills/clip ~/.local/bin/clip
set -euo pipefail

REPO_RAW="https://raw.githubusercontent.com/jinhuang712/claude-code-clip/main"
DEST="${HOME}/.claude/skills/clip"
BIN_DIR="${HOME}/.local/bin"
BIN="${BIN_DIR}/clip"

[ "$(uname -s)" = "Darwin" ] || { echo "error: clip is macOS-only (needs NSPasteboard / pbcopy)" >&2; exit 1; }
command -v curl >/dev/null 2>&1 || { echo "error: curl is required" >&2; exit 1; }

# Refuse to write through a dev symlink. install.sh (the one in the repo root)
# links ~/.claude/skills/clip → the checkout; curl -o would then follow the link
# and overwrite files inside that repo, silently discarding uncommitted work.
if [ -L "${DEST}" ]; then
  echo "This looks like a dev install — ${DEST}" >&2
  echo "is a symlink to $(readlink "${DEST}")." >&2
  echo >&2
  echo "Writing here would overwrite files in that checkout. Nothing changed." >&2
  echo "Update the checkout with git instead; or to switch to a copy install:" >&2
  echo "  rm ${DEST} && curl -fsSL https://jinhuang712.github.io/claude-code-clip/install.sh | bash" >&2
  exit 1
fi

echo "Installing the /clip skill → ${DEST}"
mkdir -p "${DEST}/scripts"
curl -fsSL "${REPO_RAW}/SKILL.md"                      -o "${DEST}/SKILL.md"
curl -fsSL "${REPO_RAW}/scripts/clip"                  -o "${DEST}/scripts/clip"
curl -fsSL "${REPO_RAW}/scripts/pbwrite.applescript"   -o "${DEST}/scripts/pbwrite.applescript"
chmod +x "${DEST}/scripts/clip"

echo "Linking the CLI → ${BIN}"
mkdir -p "${BIN_DIR}"
ln -sfn "${DEST}/scripts/clip" "${BIN}"

"${BIN}" -h >/dev/null 2>&1 || { echo "error: clip -h failed after install" >&2; exit 1; }

echo "✓ Done."
echo "  Terminal:  clip <path>            (paste with ⌘V — you get the file)"
echo "  In Claude: restart the session, then /clip <path>"
case ":${PATH}:" in
  *":${BIN_DIR}:"*) ;;
  *) echo
     echo "  Note: ${BIN_DIR} is not on your PATH — add it to ~/.zshenv:"
     echo "    export PATH=\"\$HOME/.local/bin:\$PATH\"" ;;
esac
