#!/bin/bash

# 根据 CSV 文件中标记为删除的目录执行删除操作
# 用法: ./delete_from_csv.sh [CSV文件] [基础目录]
#
# CSV 文件格式: 序号,平台,区域,版本,更新时间,大小,分类,备注,完整路径,是否删除,
# 最后一列"是否删除"为 1 表示需要删除

# 显示用法信息
show_usage() {
    echo "用法: $0 [CSV文件] [基础目录]"
    echo ""
    echo "根据 CSV 文件中标记为删除的目录执行删除操作"
    echo ""
    echo "参数:"
    echo "  CSV文件    - 包含删除标记的 CSV 文件，默认为 ready_to_delete.csv"
    echo "  基础目录   - 目录的基础路径，默认为当前目录"
    echo ""
    echo "示例:"
    echo "  $0                                    # 使用默认文件和当前目录"
    echo "  $0 ready_to_delete.csv /path/to/base # 指定文件和基础目录"
    echo ""
}

# 检查帮助参数
if [ "$1" = "--help" ] || [ "$1" = "-h" ]; then
    show_usage
    exit 0
fi

# 设置参数
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
CSV_FILE="${1:-$SCRIPT_DIR/ready_to_delete.csv}"
BASE_DIR="${2:-.}"

# 检查 CSV 文件是否存在
if [ ! -f "$CSV_FILE" ]; then
    echo "错误: CSV 文件不存在: $CSV_FILE"
    exit 1
fi

# 生成报告文件名
TIMESTAMP=$(date "+%Y%m%d_%H%M%S")
REPORT_FILE="$SCRIPT_DIR/delete_report_$TIMESTAMP.txt"

echo "=========================================="
echo "目录删除工具"
echo "=========================================="
echo "CSV 文件: $CSV_FILE"
echo "基础目录: $BASE_DIR"
echo "报告文件: $REPORT_FILE"
echo ""

# 解析 CSV 文件，获取需要删除的目录
declare -a DIRS_TO_DELETE=()
declare -a DIRS_INFO=()
TOTAL_SIZE_GB=0

echo "正在分析需要删除的目录..."
echo ""

# 跳过表头，读取 CSV 文件
# 注意：使用 || [ -n "$seq" ] 确保读取没有换行符的最后一行
line_num=0
while IFS=',' read -r seq platform region version update_time size category note path delete_flag rest || [ -n "$seq" ]; do
    line_num=$((line_num + 1))
    
    # 跳过表头
    if [ $line_num -eq 1 ]; then
        continue
    fi
    
    # 跳过空行
    if [ -z "$seq" ]; then
        continue
    fi
    
    # 检查删除标记是否为 1
    if [ "$delete_flag" = "1" ]; then
        full_path="$BASE_DIR/$path"
        
        # 解析大小（转换为 GB）
        size_value=0
        if [[ "$size" =~ ^([0-9.]+)G$ ]]; then
            size_value="${BASH_REMATCH[1]}"
        elif [[ "$size" =~ ^([0-9.]+)M$ ]]; then
            size_value=$(echo "scale=3; ${BASH_REMATCH[1]} / 1024" | bc 2>/dev/null || echo "0")
        elif [[ "$size" =~ ^([0-9.]+)K$ ]]; then
            size_value=$(echo "scale=6; ${BASH_REMATCH[1]} / 1024 / 1024" | bc 2>/dev/null || echo "0")
        fi
        
        # 检查目录是否存在
        if [ -d "$full_path" ]; then
            DIRS_TO_DELETE+=("$full_path")
            DIRS_INFO+=("$seq|$platform|$region|$version|$update_time|$size|$category|$note|$path")
            TOTAL_SIZE_GB=$(echo "$TOTAL_SIZE_GB + $size_value" | bc 2>/dev/null || echo "$TOTAL_SIZE_GB")
        else
            echo "  [跳过] 目录不存在: $full_path"
        fi
    fi
done < "$CSV_FILE"

echo ""
echo "=========================================="
echo "待删除目录清单"
echo "=========================================="
echo ""

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

# 显示待删除目录
printf "%-4s | %-10s | %-25s | %-6s | %-20s | %-8s | %-8s | %s\n" "序号" "平台" "区域" "版本" "更新时间" "大小" "分类" "备注"
echo "----------------------------------------------------------------------------------------------------------------------"

for info in "${DIRS_INFO[@]}"; do
    IFS='|' read -r seq platform region version update_time size category note path <<< "$info"
    printf "%-4s | %-10s | %-25s | %-6s | %-20s | %-8s | %-8s | %s\n" "$seq" "$platform" "$region" "$version" "$update_time" "$size" "$category" "$note"
done

echo ""
echo "=========================================="
echo "统计信息"
echo "=========================================="
echo "待删除目录数量: ${#DIRS_TO_DELETE[@]} 个"
echo "预计释放空间: 约 ${TOTAL_SIZE_GB} GB"
echo ""

# 二次确认
echo "=========================================="
echo "⚠️  警告: 删除操作不可恢复！"
echo "=========================================="
echo ""
read -p "确认删除以上 ${#DIRS_TO_DELETE[@]} 个目录吗？请输入 'yes' 确认: " confirm

if [ "$confirm" != "yes" ]; then
    echo ""
    echo "操作已取消"
    exit 0
fi

echo ""
echo "开始删除..."
echo ""

# 开始写入报告
{
    echo "=========================================="
    echo "目录删除报告"
    echo "=========================================="
    echo "执行时间: $(date '+%Y-%m-%d %H:%M:%S')"
    echo "CSV 文件: $CSV_FILE"
    echo "基础目录: $BASE_DIR"
    echo ""
    echo "=========================================="
    echo "删除详情"
    echo "=========================================="
    echo ""
} > "$REPORT_FILE"

# 执行删除
SUCCESS_COUNT=0
FAIL_COUNT=0
DELETED_SIZE_GB=0

for i in "${!DIRS_TO_DELETE[@]}"; do
    dir="${DIRS_TO_DELETE[$i]}"
    info="${DIRS_INFO[$i]}"
    
    IFS='|' read -r seq platform region version update_time size category note path <<< "$info"
    
    echo "  删除 [$((i+1))/${#DIRS_TO_DELETE[@]}]: $path"
    
    # 解析大小
    size_value=0
    if [[ "$size" =~ ^([0-9.]+)G$ ]]; then
        size_value="${BASH_REMATCH[1]}"
    elif [[ "$size" =~ ^([0-9.]+)M$ ]]; then
        size_value=$(echo "scale=3; ${BASH_REMATCH[1]} / 1024" | bc 2>/dev/null || echo "0")
    fi
    
    # 执行删除
    if rm -rf "$dir" 2>/dev/null; then
        echo "    ✓ 删除成功"
        SUCCESS_COUNT=$((SUCCESS_COUNT + 1))
        DELETED_SIZE_GB=$(echo "$DELETED_SIZE_GB + $size_value" | bc 2>/dev/null || echo "$DELETED_SIZE_GB")
        
        # 写入报告
        echo "[成功] $path ($size)" >> "$REPORT_FILE"
    else
        echo "    ✗ 删除失败"
        FAIL_COUNT=$((FAIL_COUNT + 1))
        
        # 写入报告
        echo "[失败] $path ($size)" >> "$REPORT_FILE"
    fi
done

echo ""
echo "=========================================="
echo "删除完成"
echo "=========================================="
echo ""

# 写入报告统计
{
    echo ""
    echo "=========================================="
    echo "统计信息"
    echo "=========================================="
    echo "成功删除: $SUCCESS_COUNT 个目录"
    echo "删除失败: $FAIL_COUNT 个目录"
    echo "释放空间: 约 ${DELETED_SIZE_GB} GB"
    echo ""
    echo "=========================================="
    echo "报告生成完成"
    echo "=========================================="
} >> "$REPORT_FILE"

# 显示统计
echo "成功删除: $SUCCESS_COUNT 个目录"
echo "删除失败: $FAIL_COUNT 个目录"
echo "释放空间: 约 ${DELETED_SIZE_GB} GB"
echo ""
echo "详细报告已保存到: $REPORT_FILE"
echo ""

# 显示报告内容
echo "=========================================="
echo "报告内容预览"
echo "=========================================="
cat "$REPORT_FILE"
