#!/bin/sh
# china-etax-wizard Skill installer (macOS / Linux).
# 只做四件事：下载、校验 SHA-256、解压、复制到 Skill 目录（旧版移到备份）。不运行包里其他任何东西。
set -eu

BASE="https://www.paibaowork.com/skills/china-etax-wizard"
PKG="china-etax-wizard-skill.tar.gz"
SKILL="china-etax-wizard"
BACKUP="$HOME/.config/china-etax/skill-backups"

FILE=""
SHA=""
AGENT="all"
while [ $# -gt 0 ]; do
  case "$1" in
    --file)   FILE="$2"; shift 2 ;;
    --sha256) SHA="$2"; shift 2 ;;
    --agent)  AGENT="$2"; shift 2 ;;
    --dir)    EXTRA_DIR="$2"; shift 2 ;;
    *) echo "unknown arg: $1" >&2; exit 2 ;;
  esac
done

TMP=$(mktemp -d 2>/dev/null || mktemp -d -t cetax)
trap 'rm -rf "$TMP"' EXIT

if [ -n "$FILE" ]; then
  cp "$FILE" "$TMP/$PKG"
else
  echo "下载 $BASE/latest/$PKG ..."
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL "$BASE/latest/$PKG" -o "$TMP/$PKG"
  else
    wget -qO "$TMP/$PKG" "$BASE/latest/$PKG"
  fi
fi

# 校验 SHA-256
if [ -z "$SHA" ] && [ -z "$FILE" ]; then
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL "$BASE/latest/$PKG.sha256" -o "$TMP/$PKG.sha256" || true
  else
    wget -qO "$TMP/$PKG.sha256" "$BASE/latest/$PKG.sha256" || true
  fi
  [ -s "$TMP/$PKG.sha256" ] && SHA=$(awk '{print $1}' "$TMP/$PKG.sha256")
fi
if [ -n "$SHA" ]; then
  if command -v shasum >/dev/null 2>&1; then
    GOT=$(shasum -a 256 "$TMP/$PKG" | awk '{print $1}')
  else
    GOT=$(sha256sum "$TMP/$PKG" | awk '{print $1}')
  fi
  if [ "$GOT" != "$SHA" ]; then
    echo "SHA-256 校验失败，停止安装。" >&2
    echo "  期望 $SHA" >&2
    echo "  实际 $GOT" >&2
    exit 1
  fi
  echo "SHA-256 校验通过。"
else
  echo "未提供 SHA-256，跳过校验（建议从官网 .sha256 核对）。"
fi

tar -xzf "$TMP/$PKG" -C "$TMP"
[ -d "$TMP/skills/$SKILL" ] || { echo "包结构异常：缺少 skills/$SKILL" >&2; exit 1; }

install_one() {
  DIR="$1"
  mkdir -p "$DIR"
  if [ -d "$DIR/$SKILL" ]; then
    mkdir -p "$BACKUP"
    STAMP=$(date +%Y%m%d%H%M%S)
    mv "$DIR/$SKILL" "$BACKUP/$SKILL-$STAMP"
    echo "旧版已备份到 $BACKUP/$SKILL-$STAMP"
  fi
  cp -R "$TMP/skills/$SKILL" "$DIR/$SKILL"
  echo "已安装到 $DIR/$SKILL"
}

case "$AGENT" in
  claude) install_one "$HOME/.claude/skills" ;;
  codex)  install_one "$HOME/.agents/skills" ;;
  doubao)
    D="$HOME/Library/Application Support/Doubao/Default/.doubao/agent_mode/workspace/.user_skills"
    install_one "$D" ;;
  all)
    install_one "$HOME/.claude/skills"
    install_one "$HOME/.agents/skills"
    if [ "$(uname -s)" = "Darwin" ]; then
      D="$HOME/Library/Application Support/Doubao/Default/.doubao/agent_mode/workspace/.user_skills"
      install_one "$D"
    fi
    ;;
  custom) install_one "$EXTRA_DIR" ;;
  *) echo "unknown --agent: $AGENT" >&2; exit 2 ;;
esac

echo "完成。请阅读 $SKILL/SKILL.md：登录、刷脸、验证码、最终提交由你本人操作。"
