#!/usr/bin/env bash
# Install canonical Gitea workflow skill into Codex skills dir (#551).
# Symlinks the in-repo skills/llm-project-workflow package under the names
# gitea-workflow, llm-project-workflow, and git-pr-workflows.
set -euo pipefail

usage() {
  cat <<'EOF'
usage: scripts/install-codex-workflow-skill.sh [--dry-run] [--skills-dir DIR]

Symlink the portable skills/llm-project-workflow package into the Codex
skills directory under the canonical names:
  gitea-workflow
  llm-project-workflow
  git-pr-workflows

Defaults:
  skills dir: $CODEX_HOME/skills or ~/.codex/skills
  source:     <repo>/skills/llm-project-workflow
EOF
}

dry_run=0
skills_dir=""
while [[ "${1:-}" == --* ]]; do
  case "$1" in
    --dry-run) dry_run=1 ;;
    --skills-dir)
      shift
      skills_dir="${1:-}"
      ;;
    --help|-h) usage; exit 0 ;;
    *) usage >&2; exit 2 ;;
  esac
  shift
done

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repo_root="$(cd "$script_dir/.." && pwd)"
source_skill="$repo_root/skills/llm-project-workflow"

if [[ ! -f "$source_skill/SKILL.md" ]]; then
  echo "Error: missing $source_skill/SKILL.md" >&2
  exit 1
fi

if [[ -z "$skills_dir" ]]; then
  if [[ -n "${CODEX_HOME:-}" ]]; then
    skills_dir="$CODEX_HOME/skills"
  else
    skills_dir="${HOME}/.codex/skills"
  fi
fi

names=(gitea-workflow llm-project-workflow git-pr-workflows)

echo "source: $source_skill"
echo "codex skills dir: $skills_dir"

if [[ "$dry_run" -eq 0 ]]; then
  mkdir -p "$skills_dir"
fi

for name in "${names[@]}"; do
  target="$skills_dir/$name"
  if [[ "$dry_run" -eq 1 ]]; then
    echo "dry-run: ln -sfn $source_skill $target"
    continue
  fi
  if [[ -e "$target" || -L "$target" ]]; then
    if [[ -L "$target" ]]; then
      rm -f "$target"
    else
      echo "Error: $target exists and is not a symlink (refuse to overwrite)" >&2
      exit 1
    fi
  fi
  ln -sfn "$source_skill" "$target"
  echo "linked $target -> $source_skill"
done

echo "done. Restart Codex so skills reload."
