#!/bin/sh
# SentisCAD: installs the `sentiscad` command, then connects your coding agents to
# SentisCAD so they can design parts with you. Read it first if you like: it downloads one
# file and runs it.
set -eu

WEB='https://app.sentiscad.com'
API='https://api.sentiscad.com'

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

case "$(uname -s)" in
  Darwin) os=darwin ;;
  Linux) os=linux ;;
  *) fail "this installer is for macOS and Linux. On Windows, see $WEB/agent" ;;
esac
case "$(uname -m)" in
  arm64 | aarch64) arch=arm64 ;;
  x86_64 | amd64) arch=amd64 ;;
  *) fail "no build for $(uname -m) yet" ;;
esac
[ -n "$API" ] || fail "this server has no API address set (PUBLIC_API_URL)"

bin="${SENTISCAD_BIN:-$HOME/.local/bin}"
mkdir -p "$bin"
tmp="$(mktemp "${TMPDIR:-/tmp}/sentiscad.XXXXXX")"
trap 'rm -f "$tmp"' EXIT
command -v curl >/dev/null 2>&1 || fail "curl is needed"
curl -fsSL "$WEB/cli/sentiscad-$os-$arch" -o "$tmp" || fail "could not download sentiscad for $os-$arch"
chmod +x "$tmp"
# Another program called sentiscad there (the local app, installed with uv) is kept, as
# sentiscad-local, rather than written over.
if [ -e "$bin/sentiscad" ] || [ -L "$bin/sentiscad" ]; then
  if ! "$bin/sentiscad" version 2>/dev/null | grep -q '^sentiscad '; then
    mv "$bin/sentiscad" "$bin/sentiscad-local"
    say "Your other sentiscad command is now sentiscad-local."
  fi
fi
mv "$tmp" "$bin/sentiscad"
trap - EXIT

case ":$PATH:" in
  *":$bin:"*) ;;
  *) say "Note: $bin is not on your PATH. Add it, or run $bin/sentiscad." ;;
esac

exec "$bin/sentiscad" setup --web "$WEB" --api "$API"
