#!/bin/sh
# Installs sictl, the Solinter CLI, and optionally its agent skill.
#
#   curl -fsSL https://releases.solinter.net/sictl/install.sh | sh
#   wget -qO- https://releases.solinter.net/sictl/install.sh | sh
#   curl -fsSL https://releases.solinter.net/sictl/install.sh | SICTL_SKILL=auto sh   # + the skill
#
# Linux and macOS, amd64 and arm64; on Windows, the same command in Git Bash (or MSYS2, Cygwin)
# installs sictl.exe for x86_64. On macOS, sictl keeps its token in a 0600 file, not the Keychain.
#
# Environment:
#   SICTL_VERSION       a version such as 0.1.0 (default: the one in <releases>/latest)
#   SICTL_INSTALL_DIR   where to put the binary (default: /usr/local/bin if writable, else ~/.local/bin)
#   SICTL_RELEASES_URL  the release root (default: https://releases.solinter.net/sictl)
#   SICTL_SKILL         also install the agent skill of the same version, for: auto (the agents found
#                       in your home directory), or any of claude, codex, cursor, separated by spaces
#                       or commas. claude: ~/.claude/skills; codex: ~/.agents/skills, which Cursor
#                       reads too; cursor: ~/.cursor/skills. Default: none.
#   SICTL_SKILL_DIR     install the skill into <dir>/sictl instead, e.g. a repository's .agents/skills
#   SICTL_SKILL_ONLY    1: install the skill only, for the sictl already on the PATH (its version,
#                       unless SICTL_VERSION is set); works on any system with tar
#
# Every download is checked against SHA256SUMS; when a release is signed, and minisign is installed,
# the signature of SHA256SUMS is checked too. It never uses sudo: pick a writable directory. A skill
# folder is replaced only when this script installed it; a link (such as a development checkout)
# or a folder of your own is left alone.
set -eu

# Filled in by ci/dist.sh when the release is signed.
SICTL_MINISIGN_PUBLIC_KEY='RWRK5Qo0dUJxGbs1hLye59iNp8nqAW3NwWY9NnGtutIqyT4Z60Vq/YeW'

base=${SICTL_RELEASES_URL:-https://releases.solinter.net/sictl}
base=${base%/}

say() { printf 'sictl install: %s\n' "$*" >&2; }
fail() { say "error: $*"; exit 1; }

fetch() {  # <url> <file> [message on failure]
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL --retry 3 -o "$2" "$1" || fail "${3:-cannot download $1}"
  elif command -v wget >/dev/null 2>&1; then
    wget -q -O "$2" "$1" || fail "${3:-cannot download $1}"
  else
    fail "curl or wget is required"
  fi
}

sha256() {
  if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | cut -d' ' -f1
  elif command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | cut -d' ' -f1
  elif command -v openssl >/dev/null 2>&1; then openssl dgst -sha256 "$1" | sed 's/.*= *//'
  else fail "sha256sum, shasum or openssl is required to verify the download"; fi
}

verify() {  # <file> <entry in SHA256SUMS>
  expected=$(awk -v p="$2" '$2 == p { print $1 }' "$tmp/SHA256SUMS")
  [ -n "$expected" ] || fail "SHA256SUMS of $version has no entry for $2"
  actual=$(sha256 "$1")
  [ "$expected" = "$actual" ] || fail "checksum mismatch for $2: expected $expected, got $actual"
}

# ---- Where the skill goes, checked before anything is downloaded ----
skill_only=${SICTL_SKILL_ONLY:-0}
case $skill_only in 0 | 1) ;; *) fail "SICTL_SKILL_ONLY must be 0 or 1" ;; esac
skill_roots=""
add_root() {  # <skills directory>; each once
  case "
$skill_roots
" in
    *"
$1
"*) ;;
    *) skill_roots="${skill_roots:+$skill_roots
}$1" ;;
  esac
}
if [ -n "${SICTL_SKILL_DIR:-}" ]; then
  add_root "${SICTL_SKILL_DIR%/}"
else
  for agent in $(printf '%s' "${SICTL_SKILL:-}" | tr ',' ' '); do
    case $agent in
      none) ;;
      auto)
        # Cursor also reads ~/.claude/skills and ~/.agents/skills: give it its own folder only when
        # neither is there, so it doesn't list the skill twice.
        [ ! -d "${HOME:?HOME is not set}/.claude" ] || add_root "$HOME/.claude/skills"
        if [ -d "$HOME/.codex" ] || [ -d "$HOME/.agents" ]; then add_root "$HOME/.agents/skills"; fi
        if [ -z "$skill_roots" ] && [ -d "$HOME/.cursor" ]; then add_root "$HOME/.cursor/skills"; fi
        [ -n "$skill_roots" ] || say "SICTL_SKILL=auto: no ~/.claude, ~/.codex, ~/.agents or ~/.cursor; no skill installed"
        ;;
      claude) add_root "${HOME:?HOME is not set}/.claude/skills" ;;
      codex | agents) add_root "${HOME:?HOME is not set}/.agents/skills" ;;
      cursor) add_root "${HOME:?HOME is not set}/.cursor/skills" ;;
      *) fail "SICTL_SKILL: unknown agent '$agent' (auto, claude, codex or cursor)" ;;
    esac
  done
fi
if [ "$skill_only" = 1 ] && [ -z "$skill_roots" ]; then
  fail "SICTL_SKILL_ONLY=1 needs SICTL_SKILL or SICTL_SKILL_DIR"
fi

# ---- The binary's platform ----
if [ "$skill_only" = 0 ]; then
  case "$(uname -s)" in
    Linux) os=linux name=sictl ;;
    MINGW* | MSYS* | CYGWIN*) os=windows name=sictl.exe ;;
    Darwin) os=darwin name=sictl ;;
    *) fail "unsupported system $(uname -s)" ;;
  esac
  case "$(uname -m)" in
    x86_64 | amd64) platform=$os-amd64 ;;
    aarch64 | arm64) platform=$os-arm64 ;;
    *) fail "unsupported architecture $(uname -m)" ;;
  esac
  [ "$platform" != windows-arm64 ] || fail "there is no Windows arm64 build; Windows on Arm runs windows-amd64/sictl.exe"
fi

tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT INT TERM

version=${SICTL_VERSION:-}
if [ -z "$version" ] && [ "$skill_only" = 1 ] && command -v sictl >/dev/null 2>&1; then
  version=$(sictl version 2>/dev/null | awk '/^Client Version:/ { print $3 }')
  [ -z "$version" ] || say "the skill for the sictl on your PATH, $version"
fi
if [ -z "$version" ]; then
  fetch "$base/latest" "$tmp/latest"
  version=$(tr -d ' \r\n' < "$tmp/latest")
fi
case $version in
  *[!0-9A-Za-z.+-]*) fail "'$version' is not a version" ;;
  [0-9]*.[0-9]*.[0-9]*) ;;
  *) fail "'$version' is not a version" ;;
esac

fetch "$base/$version/SHA256SUMS" "$tmp/SHA256SUMS"
if [ -n "$SICTL_MINISIGN_PUBLIC_KEY" ]; then
  if command -v minisign >/dev/null 2>&1; then
    fetch "$base/$version/SHA256SUMS.minisig" "$tmp/SHA256SUMS.minisig" \
      "cannot download the signature of sictl $version ($base/$version/SHA256SUMS.minisig); if $version was released unsigned, set SICTL_VERSION to a signed version"
    minisign -Vq -P "$SICTL_MINISIGN_PUBLIC_KEY" -m "$tmp/SHA256SUMS" -x "$tmp/SHA256SUMS.minisig" \
      || fail "the signature of SHA256SUMS does not verify"
    say "signature verified"
  else
    say "minisign is not installed: the checksum is verified, the signature is not"
  fi
fi
if [ -n "$skill_roots" ] && ! grep -q ' skill/sictl-skill\.tar\.gz$' "$tmp/SHA256SUMS"; then
  fail "sictl $version was released without the agent skill; set SICTL_VERSION to a later version"
fi

# ---- The binary ----
if [ "$skill_only" = 0 ]; then
  say "downloading sictl $version for $platform"
  fetch "$base/$version/$platform/$name" "$tmp/$name"
  verify "$tmp/$name" "$platform/$name"

  dir=${SICTL_INSTALL_DIR:-}
  if [ -z "$dir" ]; then
    if [ -d /usr/local/bin ] && [ -w /usr/local/bin ]; then dir=/usr/local/bin
    else dir="${HOME:?HOME is not set}/.local/bin"; fi
  fi
  mkdir -p "$dir" || fail "cannot create $dir"
  [ -w "$dir" ] || fail "$dir is not writable: set SICTL_INSTALL_DIR to a directory you can write"
  chmod 755 "$tmp/$name"
  mv "$tmp/$name" "$dir/$name" || fail "cannot write $dir/$name"

  say "installed $dir/$name"
  case ":$PATH:" in
    *":$dir:"*) ;;
    *) say "$dir is not on your PATH; add it, e.g. export PATH=\"$dir:\$PATH\"" ;;
  esac
  "$dir/$name" version
fi

# ---- The agent skill (docs/agents.md) ----
if [ -n "$skill_roots" ]; then
  say "downloading the sictl $version agent skill"
  fetch "$base/$version/skill/sictl-skill.tar.gz" "$tmp/sictl-skill.tar.gz"
  verify "$tmp/sictl-skill.tar.gz" skill/sictl-skill.tar.gz
  mkdir "$tmp/skill"
  tar -xzf "$tmp/sictl-skill.tar.gz" -C "$tmp/skill" || fail "cannot unpack the skill"
  [ -f "$tmp/skill/SKILL.md" ] || fail "the skill archive has no SKILL.md"
  printf '%s\n' "$version" > "$tmp/skill/.sictl-skill"   # marks a folder this script may replace

  old_ifs=$IFS
  IFS='
'
  for root in $skill_roots; do
    IFS=$old_ifs
    target="$root/sictl"
    if [ -L "$target" ]; then
      say "skipped $target: it is a link to $(readlink "$target"), left as it is"
    elif [ -e "$target" ] && [ ! -f "$target/.sictl-skill" ]; then
      say "skipped $target: it was not installed by this script; remove it to install here"
    else
      mkdir -p "$root" || fail "cannot create $root"
      staging="$root/.sictl-skill.new"   # hidden, so agents never list a half-copied skill
      rm -rf "$staging"
      cp -R "$tmp/skill" "$staging" || { rm -rf "$staging"; fail "cannot write in $root"; }
      rm -rf "$target"
      mv "$staging" "$target" || fail "cannot write $target"
      say "installed the skill in $target"
    fi
  done
  IFS=$old_ifs
fi
