#!/usr/bin/env bash
# 生生 启动器：shengsheng up | down | restart | open | attest | status | uninstall [--purge] | update
set -euo pipefail
SELF="$(cd "$(dirname "$(readlink "$0" || echo "$0")")" && pwd)"
APP="$(cd "$SELF/.." && pwd)"; SH_HOME="${SHENGSHENG_HOME:-$HOME/.shengsheng}"
export PATH="$PATH:/usr/sbin:/sbin"  # lsof、sysctl 在这里；从 launchd 或精简环境里调用时 PATH 可能没有
[ -x "$SH_HOME/node/bin/node" ] && export PATH="$SH_HOME/node/bin:$PATH"
PORT=$((5199 + ${BORNED_PORT_OFFSET:-0})); URL="http://127.0.0.1:$PORT/home/"
cd "$APP"
case "${1:-up}" in
  up) npm run -s borned:up; [ "${SHENGSHENG_NO_OPEN:-}" = "1" ] || open "$URL";;
  down) npm run -s borned:down -- --force;;
  restart) npm run -s borned:restart;;
  open) open "$URL";;
  attest) npm run -s borned:sandbox-test && npm run -s borned:restart acpd;;
  status) npm run -s borned:ports;;
  update) curl -fsSL --proto '=https' "${SHENGSHENG_BASE_URL:-https://shengsheng.wordm.us/download}/install.sh" | bash;;
  uninstall)
    npm run -s borned:down -- --force >/dev/null 2>&1 || true
    if [ "${2:-}" = "--purge" ]; then
      for p in anthropic openai google fal; do security delete-generic-password -s "ai.borned.key.$p" -a borned >/dev/null 2>&1 || true; done
      rm -rf "$SH_HOME"; echo "生生和它的数据、钥匙都删掉了。服务商那边的钥匙要你自己去作废。"
    else
      B="$SH_HOME/data-backup-$(date +%Y%m%d%H%M%S)"; [ -d "$APP/.borned" ] && mv "$APP/.borned" "$B"
      rm -rf "$APP" "$SH_HOME/bin" "$SH_HOME/node"; echo "生生删掉了。你的数据留在 $B（要一起删：shengsheng uninstall --purge，或直接删这个文件夹）。"
    fi;;
  *) echo "用法：shengsheng up | down | restart | open | attest | status | uninstall [--purge] | update"; exit 2;;
esac
