#!/bin/bash

# 完成公证流程脚本
# 作者: Collins

set -e

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

# 颜色输出
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_status() {
    local submission_id="$1"
    
    log_info "检查提交状态: $submission_id"
    
    local status=$(xcrun notarytool info "$submission_id" \
        --apple-id "$APPLE_ID" \
        --password "$PASSWORD" \
        --team-id "$TEAM_ID" \
        --output-format json | jq -r '.status')
    
    echo "$status"
}

# 等待完成
wait_for_completion() {
    local submission_id="$1"
    
    log_info "等待公证完成..."
    
    while true; do
        local status=$(check_status "$submission_id")
        
        case "$status" in
            "Accepted")
                log_success "公证成功！"
                return 0
                ;;
            "Invalid")
                log_error "公证失败！"
                show_log "$submission_id"
                return 1
                ;;
            "In Progress")
                log_info "状态: 进行中... ($(date))"
                sleep 30
                ;;
            *)
                log_warning "未知状态: $status"
                sleep 30
                ;;
        esac
    done
}

# 显示日志
show_log() {
    local submission_id="$1"
    
    log_info "获取公证日志..."
    
    xcrun notarytool log "$submission_id" \
        --apple-id "$APPLE_ID" \
        --password "$PASSWORD" \
        --team-id "$TEAM_ID"
}

# 装订公证
staple_notarization() {
    log_info "装订公证到 DMG..."
    
    if [ ! -f "$DMG_FILE" ]; then
        log_error "DMG 文件不存在: $DMG_FILE"
        return 1
    fi
    
    xcrun stapler staple "$DMG_FILE"
    
    if [ $? -eq 0 ]; then
        log_success "装订成功！"
        return 0
    else
        log_error "装订失败！"
        return 1
    fi
}

# 验证最终结果
verify_result() {
    log_info "验证最终结果..."
    
    # 检查装订状态
    xcrun stapler validate "$DMG_FILE"
    
    if [ $? -eq 0 ]; then
        log_success "DMG 已成功装订公证！"
        log_info "现在可以在其他 Mac 上正常打开了"
    else
        log_error "DMG 装订验证失败！"
    fi
}

# 自动完成流程
auto_complete() {
    local submission_id="$1"
    
    log_info "开始自动完成流程..."
    
    # 等待完成
    if wait_for_completion "$submission_id"; then
        # 装订公证
        if staple_notarization; then
            # 验证结果
            verify_result
            log_success "整个流程完成！"
        else
            log_error "装订失败"
            return 1
        fi
    else
        log_error "公证失败"
        return 1
    fi
}

# 手动完成流程
manual_complete() {
    local submission_id="$1"
    
    log_info "手动完成流程..."
    
    # 检查当前状态
    local status=$(check_status "$submission_id")
    log_info "当前状态: $status"
    
    case "$status" in
        "Accepted")
            log_success "公证已完成，开始装订..."
            staple_notarization
            verify_result
            ;;
        "In Progress")
            log_warning "公证仍在进行中，请稍后再试"
            ;;
        "Invalid")
            log_error "公证失败，请查看日志"
            show_log "$submission_id"
            ;;
        *)
            log_warning "未知状态: $status"
            ;;
    esac
}

# 显示帮助
show_help() {
    echo "用法: $0 [选项] <submission_id>"
    echo ""
    echo "选项:"
    echo "  auto                      - 自动等待并完成"
    echo "  manual                    - 手动检查并完成"
    echo "  status                    - 仅检查状态"
    echo "  log                       - 查看日志"
    echo "  staple                    - 仅装订公证"
    echo "  verify                    - 验证结果"
    echo ""
    echo "示例:"
    echo "  $0 auto b7414dba-adb5-4e0a-9535-ae51815736c4"
    echo "  $0 manual b7414dba-adb5-4e0a-9535-ae51815736c4"
    echo "  $0 status b7414dba-adb5-4e0a-9535-ae51815736c4"
}

# 主函数
main() {
    local action="${1:-help}"
    local submission_id="$2"
    
    if [ -z "$submission_id" ] && [ "$action" != "help" ]; then
        log_error "请提供提交 ID"
        show_help
        exit 1
    fi
    
    case "$action" in
        "auto")
            auto_complete "$submission_id"
            ;;
        "manual")
            manual_complete "$submission_id"
            ;;
        "status")
            check_status "$submission_id"
            ;;
        "log")
            show_log "$submission_id"
            ;;
        "staple")
            staple_notarization
            ;;
        "verify")
            verify_result
            ;;
        "help"|*)
            show_help
            ;;
    esac
}

# 运行主函数
main "$@"
