#!/usr/bin/env bash
# DCS install (POSIX): copy the DCS package from this repo (canonical) into ~/.claude.
# Idempotent; overwrites installed files with repo versions. Run after every committed change.
#
# --target=<claude|dsh|all|auto> (default claude -- unchanged historical behavior):
#   claude  raw copy into the Claude home, exactly the body below
#   dsh     transformed payload into the DSH home (~/.dsh)
#   all     both, Claude first
#   auto    only targets whose home directory exists
# dsh/all/auto delegate to the SAME installer logic (node bin/dcs.js install
# --target ...) so the transform and the marked appends have ONE implementation;
# this script stays a thin front door for those targets. The claude body below
# is kept native so a machine without node can still refresh the Claude tree.
set -euo pipefail
repo="$(cd "$(dirname "$0")" && pwd)"

target="claude"
case "${1:-}" in
  --target=*) target="${1#--target=}" ;;
  --target)
    [ $# -ge 2 ] || { echo "error: --target requires a value" >&2; exit 1; }
    target="$2" ;;
esac
case "$target" in
  claude|dsh|all|auto) ;;
  *) echo "error: unknown --target '$target' (valid: claude|dsh|all|auto)" >&2; exit 1 ;;
esac

if [ "$target" != "claude" ]; then
  node "$repo/bin/dcs.js" install --target "$target"
  exit $?
fi

claude="${HOME}/.claude"

mkdir -p "$claude/dcs" "$claude/agents" "$claude/skills"

rsync -a --exclude '__pycache__' "$repo/dcs/" "$claude/dcs/" 2>/dev/null \
  || cp -R "$repo/dcs/." "$claude/dcs/"

cp "$repo"/agents/dcs-*.md "$claude/agents/"

for d in "$repo"/skills/dcs-*/; do
  name="$(basename "$d")"
  mkdir -p "$claude/skills/$name"
  cp -R "$d." "$claude/skills/$name/"
done

version="$(tr -d '[:space:]' < "$repo/dcs/VERSION")"
echo "DCS $version installed to $claude"
echo "NOTE: projects hold their own copy of dcs_gate.py in <project>/.claude/hooks/ -- re-run /dcs-init (or copy dcs/hooks/dcs_gate.py manually) in each onboarded project after a hook change."
