#!/bin/bash
# 生成通用安装包（APK + Agent + Hook 脚本 + 安装说明）

set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
DIST_DIR="$ROOT_DIR/dist/universal"
PKG_NAME="workphone-universal-$(date +%Y%m%d-%H%M%S)"
PKG_DIR="$DIST_DIR/$PKG_NAME"

mkdir -p "$PKG_DIR"

echo "== 1) 构建 Android APK =="
pushd "$ROOT_DIR/android-app" >/dev/null
export JAVA_HOME="${JAVA_HOME:-$(/usr/libexec/java_home -v 21)}"
export PATH="$JAVA_HOME/bin:$PATH"
./gradlew assembleDebug
popd >/dev/null

APK_PATH="$ROOT_DIR/android-app/app/build/outputs/apk/debug/app-debug.apk"
if [[ ! -f "$APK_PATH" ]]; then
  echo "APK 未生成: $APK_PATH"
  exit 1
fi

echo "== 2) 打包 Agent =="
pushd "$ROOT_DIR/agent" >/dev/null
bash package.sh
popd >/dev/null

cp "$APK_PATH" "$PKG_DIR/workphone-agent-debug.apk"
cp "$ROOT_DIR/agent/dist/agent.tar.gz" "$PKG_DIR/agent.tar.gz"
cp "$ROOT_DIR/agent/install.sh" "$PKG_DIR/install.sh"
cp "$ROOT_DIR/agent/hook/wechat_hook_v1.js" "$PKG_DIR/wechat_hook_v1.js"
cp "$ROOT_DIR/agent/hook/setup_redmi11.sh" "$PKG_DIR/setup_redmi11.sh"

cat > "$PKG_DIR/INSTALL.md" <<'EOF'
# WorkPhone 通用安装包

包含：
- `workphone-agent-debug.apk`：Android 设备端 App
- `agent.tar.gz`：Termux Python Agent 包
- `install.sh`：Termux 一键安装脚本
- `wechat_hook_v1.js`：微信 Hook 初版脚本
- `setup_redmi11.sh`：红米11 root 设备初始化脚本

## 1）安装 App

```bash
adb install -r workphone-agent-debug.apk
```

## 2）安装 Agent（Termux）

```bash
curl -sL http://<server>:8899/install.sh | bash -s -- --server ws://<server>:8899/ws/device
```

## 3）部署 Hook 脚本

```bash
curl -s -X POST "http://<server>:8899/api/v3/scripts?module_id=wechat_hook_v1&version=1.0.0" \
  -F "file=@wechat_hook_v1.js"
```

## 4）红米11 Root 探测

```bash
curl -s "http://<server>:8899/api/v3/devices/<device_id>/modules"
```

当返回 `supports_hook=true` 且 `frida_version` 有值，表示 Hook 环境可用。
EOF

tar czf "$DIST_DIR/${PKG_NAME}.tar.gz" -C "$DIST_DIR" "$PKG_NAME"

echo "完成："
echo "目录包: $PKG_DIR"
echo "压缩包: $DIST_DIR/${PKG_NAME}.tar.gz"
