#!/bin/bash

# 删除windows、ios、android目录下指定前缀目录的特定版本目录
# 用法: ./delete_gungho_versions.sh <prefix> [list|delete]
# prefix: 目录前缀，如 gungho、na_
# list: 只列出将要删除的目录
# delete: 执行删除操作

# 显示用法信息
show_usage() {
    echo "用法: $0 <prefix> [list|delete]"
    echo "  prefix - 目录前缀，如 gungho、na_"
    echo "  list   - 列出将要删除的目录"
    echo "  delete - 执行删除操作"
    echo ""
    echo "示例:"
    echo "  $0 gungho list    # 列出gungho开头的目录中的1.0和1.1版本"
    echo "  $0 na_ delete     # 删除na_开头的目录中的1.0和1.1版本"
    echo ""
}

# 检查参数
if [ $# -lt 2 ]; then
    echo "错误: 参数不足"
    show_usage
    exit 1
fi

PREFIX="$1"
ACTION="$2"

if [ "$ACTION" != "list" ] && [ "$ACTION" != "delete" ]; then
    echo "错误: 无效的操作 '$ACTION'"
    show_usage
    exit 1
fi

echo "正在查找${PREFIX}开头的目录中的1.0和1.1版本..."
echo ""

# 定义要搜索的根目录
ROOT_DIRS=("windows" "ios" "android")

# 定义要删除的版本目录
VERSIONS=("1.0" )

# 存储找到的目录
DIRS_TO_DELETE=()

# 遍历每个根目录
for root_dir in "${ROOT_DIRS[@]}"; do
    if [ -d "$root_dir" ]; then
        if [ "$ACTION" = "list" ]; then
            echo "检查 $root_dir 目录..."
        fi
        
        # 查找指定前缀的目录
        for target_dir in "$root_dir"/${PREFIX}*; do
            if [ -d "$target_dir" ]; then
                if [ "$ACTION" = "list" ]; then
                    echo "  找到${PREFIX}目录: $target_dir"
                fi
                
                # 检查每个版本目录
                for version in "${VERSIONS[@]}"; do
                    version_path="$target_dir/$version"
                    if [ -d "$version_path" ]; then
                        if [ "$ACTION" = "list" ]; then
                            echo "    找到版本目录: $version_path"
                        fi
                        DIRS_TO_DELETE+=("$version_path")
                    fi
                done
            fi
        done
    else
        if [ "$ACTION" = "list" ]; then
            echo "目录 $root_dir 不存在，跳过"
        fi
    fi
done

echo ""
echo "========================================"
if [ "$ACTION" = "list" ]; then
    echo "找到的目录列表:"
else
    echo "将要删除的目录列表:"
fi
echo "========================================"

if [ ${#DIRS_TO_DELETE[@]} -eq 0 ]; then
    echo "没有找到需要处理的目录"
    exit 0
fi

# 显示找到的目录
for dir in "${DIRS_TO_DELETE[@]}"; do
    echo "  $dir"
done

echo ""
echo "总共找到 ${#DIRS_TO_DELETE[@]} 个目录"

# 如果是list模式，直接退出
if [ "$ACTION" = "list" ]; then
    exit 0
fi

# 如果是delete模式，询问用户确认
echo ""
read -p "确认删除以上目录吗？(y/N): " confirm

if [[ $confirm =~ ^[Yy]$ ]]; then
    echo ""
    echo "开始删除目录..."
    
    # 删除目录
    for dir in "${DIRS_TO_DELETE[@]}"; do
        if [ -d "$dir" ]; then
            echo "删除: $dir"
            rm -rf "$dir"
            if [ $? -eq 0 ]; then
                echo "  ✓ 删除成功"
            else
                echo "  ✗ 删除失败"
            fi
        else
            echo "目录 $dir 不存在，跳过"
        fi
    done
    
    echo ""
    echo "删除操作完成！"
else
    echo "操作已取消"
fi
