#!/usr/bin/env bash
# Installs the Odin "odin-api" Claude skill.
#
#   curl -fsSL https://www.odinhelp.com/skill/install.sh | bash
#
# Options (pass after `bash -s --`):
#   --dir <path>   install somewhere other than ~/.claude/skills
#   --force        overwrite an existing install
#
# Skill version: 87e24c2d1b8d
set -euo pipefail

BASE_URL="${ODIN_SKILL_BASE_URL:-https://www.odinhelp.com/skill}"
TARGET_ROOT="${HOME}/.claude/skills"
FORCE=0

while [ "$#" -gt 0 ]; do
  case "$1" in
    --dir) TARGET_ROOT="$2"; shift 2 ;;
    --force) FORCE=1; shift ;;
    -h|--help) sed -n '2,12p' "$0"; exit 0 ;;
    *) echo "Unknown option: $1" >&2; exit 2 ;;
  esac
done

DEST="${TARGET_ROOT}/odin-api"

if [ -e "${DEST}" ] && [ "${FORCE}" -ne 1 ]; then
  echo "Already installed at ${DEST}" >&2
  echo "Re-run with --force to overwrite." >&2
  exit 1
fi

command -v curl >/dev/null 2>&1 || { echo "curl is required" >&2; exit 1; }

# Stage in a temp dir so a failed download never leaves a half-written skill.
TMP="$(mktemp -d)"
trap 'rm -rf "${TMP}"' EXIT

FILES=(
  "SKILL.md|SKILL.md|644"
  "references/endpoints.md|references/endpoints.md|644"
  "references/rentredi.md|references/rentredi.md|644"
  "scripts/odin|scripts/odin.sh|755"
)

for spec in "${FILES[@]}"; do
  # spec is local|remote|mode. They differ where the CDN cannot serve an
  # extensionless object, so download the remote name but write the local one.
  rel="${spec%%|*}"
  rest="${spec#*|}"
  remote="${rest%%|*}"
  mode="${rest##*|}"
  mkdir -p "${TMP}/$(dirname "${rel}")"
  if ! curl -fsSL "${BASE_URL}/odin-api/${remote}" -o "${TMP}/${rel}"; then
    echo "Failed to download ${remote}" >&2
    exit 1
  fi
  if [ ! -s "${TMP}/${rel}" ]; then
    echo "Downloaded ${remote} but it was empty" >&2
    exit 1
  fi
  chmod "${mode}" "${TMP}/${rel}"
done

mkdir -p "${TARGET_ROOT}"
rm -rf "${DEST}"
mv "${TMP}/" "${DEST}"
trap - EXIT

cat <<EOF

Installed the odin-api skill to ${DEST}

Two things left, both one-time:

  1. Create a token: Odin dashboard -> Profile -> Personal Access Tokens
  2. Export it, along with the API address for your environment:

       export ODIN_API_TOKEN="opat_..."
       export ODIN_API_BASE_URL="https://api.odinhelp.com"

Then check it works:

       "${DEST}/scripts/odin" preflight

EOF
