#!/bin/bash

# 更新 TEAM_ID 的简单脚本

set -e

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

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"
}

# 获取 Team ID
get_team_id() {
    log_info "请提供您的 Apple Developer Team ID"
    log_info "您可以通过以下方式获取："
    log_info "1. 登录 https://developer.apple.com"
    log_info "2. 进入 'Account' -> 'Membership'"
    log_info "3. 查看 'Team ID' 字段（格式类似：ABC123DEF4）"
    echo ""
    
    read -p "请输入您的 Team ID: " team_id
    
    if [ -z "$team_id" ]; then
        log_error "Team ID 不能为空"
        exit 1
    fi
    
    # 验证 Team ID 格式（应该是10位字母数字组合）
    if [[ ! "$team_id" =~ ^[A-Z0-9]{10}$ ]]; then
        log_warning "Team ID 格式可能不正确，但继续执行"
    fi
    
    echo "$team_id"
}

# 更新配置文件
update_config() {
    local team_id=$1
    
    log_info "更新 ios_signing_config.sh 文件..."
    
    # 备份原文件
    cp ios_signing_config.sh ios_signing_config.sh.backup
    
    # 更新 Team ID
    sed -i '' "s/export TEAM_ID=\"YOUR_TEAM_ID\"/export TEAM_ID=\"$team_id\"/" ios_signing_config.sh
    
    # 更新签名身份
    sed -i '' "s/export SIGNING_IDENTITY=\"iPhone Developer: Your Name (YOUR_TEAM_ID)\"/export SIGNING_IDENTITY=\"iPhone Developer: Your Name ($team_id)\"/" ios_signing_config.sh
    sed -i '' "s/export DISTRIBUTION_IDENTITY=\"iPhone Distribution: Your Name (YOUR_TEAM_ID)\"/export DISTRIBUTION_IDENTITY=\"iPhone Distribution: Your Name ($team_id)\"/" ios_signing_config.sh
    
    log_success "配置文件已更新"
    log_info "Team ID: $team_id"
}

# 显示更新后的配置
show_config() {
    log_info "更新后的配置："
    echo "----------------------------------------"
    grep -E "export (APPLE_ID|TEAM_ID|BUNDLE_ID|SIGNING_IDENTITY)" ios_signing_config.sh
    echo "----------------------------------------"
}

# 主函数
main() {
    log_info "开始更新 TEAM_ID..."
    log_info "=========================================="
    
    local team_id=$(get_team_id)
    update_config "$team_id"
    show_config
    
    log_success "=========================================="
    log_success "TEAM_ID 更新完成！"
    log_success "=========================================="
    log_info "现在可以运行:"
    log_info "1. source ios_signing_config.sh"
    log_info "2. ./build_ios_dmg.sh"
    log_success "=========================================="
}

# 运行主函数
main "$@"
