#!/bin/bash

# 异步公证脚本 - 不等待结果

set -e

# 配置变量
APPLE_ID="xxxxxxxx@example.com"
PASSWORD="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
TEAM_ID="XXXXXXXXXX"
ZIP_FILE="build/macos/Build/Products/Release/BearVPN-1.0.0.zip"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查文件
check_file() {
    if [ ! -f "$ZIP_FILE" ]; then
        log_error "ZIP 文件不存在: $ZIP_FILE"
        exit 1
    fi
    log_success "找到文件: $ZIP_FILE"
}

# 异步提交公证
submit_async() {
    log_info "开始异步提交公证..."
    
    # 提交但不等待结果
    SUBMISSION_ID=$(xcrun notarytool submit "$ZIP_FILE" \
        --apple-id "$APPLE_ID" \
        --password "$PASSWORD" \
        --team-id "$TEAM_ID" \
        --output-format json | jq -r '.id')
    
    if [ -z "$SUBMISSION_ID" ] || [ "$SUBMISSION_ID" = "null" ]; then
        log_error "提交失败，无法获取提交 ID"
        exit 1
    fi
    
    log_success "提交成功！"
    log_info "提交 ID: $SUBMISSION_ID"
    
    # 保存提交 ID 到文件
    echo "$SUBMISSION_ID" > .notarization_id
    echo "$(date)" > .notarization_time
    
    log_info "提交 ID 已保存到 .notarization_id"
    log_warning "请稍后使用 ./check_notarization_status.sh 检查状态"
}

# 显示后续操作
show_next_steps() {
    log_success "=========================================="
    log_success "异步提交完成！"
    log_success "=========================================="
    log_info "提交 ID: $SUBMISSION_ID"
    log_info "提交时间: $(date)"
    log_success "=========================================="
    log_info "后续操作："
    log_info "1. 检查状态: ./check_notarization_status.sh info $SUBMISSION_ID"
    log_info "2. 查看历史: ./check_notarization_status.sh history"
    log_info "3. 实时监控: ./check_notarization_status.sh monitor"
    log_info "4. 完成后装订: xcrun stapler staple BearVPN-1.0.0-macOS-Signed.dmg"
    log_success "=========================================="
}

# 主函数
main() {
    log_info "开始异步公证提交..."
    log_info "=========================================="
    
    check_file
    submit_async
    show_next_steps
    
    log_success "提交完成，您可以继续其他工作！"
}

# 运行主函数
main "$@"
