#!/bin/bash

# 检查公证状态的脚本
# 作者: Collins

set -e

# 配置变量
APPLE_ID="xxxxxxxx@example.com"
TEAM_ID="XXXXXXXXXX"
PASSWORD="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
SUBMISSION_ID=""

# 颜色输出
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_history() {
    log_info "检查历史提交记录..."
    
    xcrun notarytool history \
        --apple-id "$APPLE_ID" \
        --password "$PASSWORD" \
        --team-id "$TEAM_ID"
}

# 检查特定提交状态
check_submission() {
    if [ -z "$SUBMISSION_ID" ]; then
        log_error "请提供提交 ID"
        log_info "使用方法: $0 <submission_id>"
        exit 1
    fi
    
    log_info "检查提交状态: $SUBMISSION_ID"
    
    xcrun notarytool info "$SUBMISSION_ID" \
        --apple-id "$APPLE_ID" \
        --password "$PASSWORD" \
        --team-id "$TEAM_ID"
}

# 检查日志
check_log() {
    if [ -z "$SUBMISSION_ID" ]; then
        log_error "请提供提交 ID"
        exit 1
    fi
    
    log_info "获取提交日志: $SUBMISSION_ID"
    
    xcrun notarytool log "$SUBMISSION_ID" \
        --apple-id "$APPLE_ID" \
        --password "$PASSWORD" \
        --team-id "$TEAM_ID"
}

# 实时监控
monitor_status() {
    log_info "开始实时监控公证状态..."
    
    while true; do
        echo "=========================================="
        echo "时间: $(date)"
        echo "=========================================="
        
        # 检查历史记录
        check_history
        
        echo "=========================================="
        echo "等待 30 秒后刷新..."
        sleep 30
    done
}

# 显示帮助
show_help() {
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  history                    - 查看历史提交记录"
    echo "  info <submission_id>       - 查看特定提交状态"
    echo "  log <submission_id>        - 查看提交日志"
    echo "  monitor                    - 实时监控状态"
    echo "  help                       - 显示此帮助"
    echo ""
    echo "示例:"
    echo "  $0 history"
    echo "  $0 info 12345678-1234-1234-1234-123456789012"
    echo "  $0 log 12345678-1234-1234-1234-123456789012"
    echo "  $0 monitor"
}

# 主函数
main() {
    case "${1:-help}" in
        "history")
            check_history
            ;;
        "info")
            SUBMISSION_ID="$2"
            check_submission
            ;;
        "log")
            SUBMISSION_ID="$2"
            check_log
            ;;
        "monitor")
            monitor_status
            ;;
        "help"|*)
            show_help
            ;;
    esac
}

# 运行主函数
main "$@"
