#!/usr/bin/env bash
# xiangqin landing 本地部署脚本 —— 上传到阿里云 OSS。
#
# 本脚本给本地手跑用（快速迭代时）；CI/CD 用 .github/workflows/deploy-landing.yml
# 自动触发（push main 到 landing/ 目录变化）。
#
# 前置：bucket agentaily-xiangqin-landing 已建 + 域名 xiangqin.agentaily.com
# 已绑（见 ~/.claude/skills/aliyun-static-site/SKILL.md）。

set -euo pipefail

LANDING_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BUCKET="${LANDING_BUCKET:-agentaily-xiangqin-landing}"
REGION="${LANDING_REGION:-cn-hangzhou}"

echo "[landing] 上传 $LANDING_DIR/index.html → oss://$BUCKET/"

# AK 来源两条：
# 1. CI：从 env OSS_ACCESS_KEY_ID / OSS_ACCESS_KEY_SECRET 读（GH workflow 配）
# 2. 本地：从 ~/xiangqin/.vault/secrets.json 读（vault install 产出）
if [ -z "${OSS_ACCESS_KEY_ID:-}" ] || [ -z "${OSS_ACCESS_KEY_SECRET:-}" ]; then
    VAULT_SECRETS="$HOME/xiangqin/.vault/secrets.json"
    if [ ! -f "$VAULT_SECRETS" ]; then
        echo "ERROR: 既无 OSS_ACCESS_KEY_ID env，又无 $VAULT_SECRETS。" >&2
        echo "HINT: cd ~/xiangqin && vault install" >&2
        exit 1
    fi
    export OSS_ACCESS_KEY_ID=$(python3 -c "import json; print(json.load(open('$VAULT_SECRETS')).get('aliyun-landing-publisher', {}).get('access_key_id', ''))")
    export OSS_ACCESS_KEY_SECRET=$(python3 -c "import json; print(json.load(open('$VAULT_SECRETS')).get('aliyun-landing-publisher', {}).get('access_key_secret', ''))")
    if [ -z "$OSS_ACCESS_KEY_ID" ]; then
        echo "ERROR: vault 里 aliyun-landing-publisher 没配" >&2
        exit 1
    fi
fi

# aliyun CLI 优先；没装则提示
if ! command -v aliyun >/dev/null 2>&1; then
    echo "ERROR: aliyun CLI 未安装。brew install aliyun-cli" >&2
    exit 1
fi

# 用 landing 专用 profile，避免改默认 profile 影响其它工具
aliyun configure set --profile landing-publisher --mode AK \
    --access-key-id "$OSS_ACCESS_KEY_ID" \
    --access-key-secret "$OSS_ACCESS_KEY_SECRET" \
    --region "$REGION" >/dev/null

aliyun ossutil cp "$LANDING_DIR/index.html" "oss://$BUCKET/index.html" \
    --cache-control "public, max-age=300, must-revalidate" \
    --content-type "text/html; charset=utf-8" \
    --profile landing-publisher \
    -f

echo "[landing] ✓ 上传完成"
HTTP_CODE=$(curl -sSL -o /dev/null -w "%{http_code}" "http://xiangqin.agentaily.com/" || echo "000")
echo "[landing] http://xiangqin.agentaily.com/ → HTTP $HTTP_CODE"
