#!/usr/bin/env bash
set -euo pipefail

TARGET="${TARGET:-cunkebao}"
REMOTE_DIR="${REMOTE_DIR:-/www/wwwroot/workphone-sdk}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SDK_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

ssh "$TARGET" "mkdir -p '$REMOTE_DIR/app' '$REMOTE_DIR/agent' '$REMOTE_DIR/deploy/baota'"

rsync -az --delete \
  --exclude '__pycache__' --exclude '*.pyc' --exclude '*.log' \
  --exclude 'data/cunke_bao_config.json' --exclude 'data/hook/events.jsonl' \
  --exclude 'data/operation_logs' --exclude 'agent/config.json' \
  "$SDK_ROOT/app/" "$TARGET:$REMOTE_DIR/app/"

rsync -az --delete \
  --exclude '__pycache__' --exclude '*.pyc' --exclude '*.log' \
  --exclude 'config.json' --exclude 'config.*.json' \
  "$SDK_ROOT/agent/" "$TARGET:$REMOTE_DIR/agent/"

rsync -az \
  "$SDK_ROOT/Dockerfile" "$SDK_ROOT/.dockerignore" "$SDK_ROOT/requirements.txt" \
  "$SDK_ROOT/docker-compose.baota.yml" "$TARGET:$REMOTE_DIR/"
rsync -az "$SDK_ROOT/deploy/baota/wpsdk.quwanzhi.com.conf" "$TARGET:$REMOTE_DIR/deploy/baota/"

ssh "$TARGET" "REMOTE_DIR='$REMOTE_DIR' bash -s" <<'REMOTE'
set -euo pipefail
cd "$REMOTE_DIR"
if [[ ! -f .env ]]; then
  umask 077
  mongo_password="$(openssl rand -hex 24)"
  api_key="$(openssl rand -hex 32)"
  pairing_token="$(openssl rand -hex 32)"
  printf 'MONGO_ROOT_USERNAME=workphone\nMONGO_ROOT_PASSWORD=%s\nAPI_KEY=%s\nDEVICE_PAIRING_TOKEN=%s\nAI_BRAIN_ENABLED=false\nAI_BRAIN_API_URL=https://kr-ai.quwanzhi.com\nAI_BRAIN_API_KEY=\n' \
    "$mongo_password" "$api_key" "$pairing_token" > .env
fi
chmod 600 .env
docker compose -f docker-compose.baota.yml up -d --build
install -d -m 755 /www/server/panel/vhost/cert/wpsdk.quwanzhi.com
install -m 644 /root/.acme.sh/quwanzhi.com_ecc/fullchain.cer /www/server/panel/vhost/cert/wpsdk.quwanzhi.com/fullchain.pem
install -m 600 /root/.acme.sh/quwanzhi.com_ecc/quwanzhi.com.key /www/server/panel/vhost/cert/wpsdk.quwanzhi.com/privkey.pem
install -m 644 deploy/baota/wpsdk.quwanzhi.com.conf /www/server/panel/vhost/nginx/wpsdk.quwanzhi.com.conf
/www/server/nginx/sbin/nginx -t
/www/server/nginx/sbin/nginx -s reload
REMOTE

echo "部署完成：https://wpsdk.quwanzhi.com/health"
