#!/bin/bash

# 列出 android、ios、windows 目录下所有子目录的最后更新时间
# 用法: ./list_dir_update_time.sh [目录路径]
# 
# 目录结构示例:
#   windows/eu_hgh/1.1/...
#   android/na_qa/2.0/...
#   ios/gungho/1.0/...
#
# 输出: 列出每个版本目录（如 windows/eu_hgh/1.1）下所有文件的最新更新时间

# 显示用法信息
show_usage() {
    echo "用法: $0 [目录路径] [输出JSON文件]"
    echo ""
    echo "列出 android、ios、windows 目录下所有子目录的最后更新时间"
    echo ""
    echo "参数:"
    echo "  目录路径     - 可选，默认为当前目录"
    echo "  输出JSON文件 - 可选，默认为 dir_update_time.json"
    echo ""
    echo "示例:"
    echo "  $0                                    # 在当前目录下查找"
    echo "  $0 /path/to/bundles                   # 在指定目录下查找"
    echo "  $0 /path/to/bundles result.json       # 指定输出文件"
    echo "  $0 //nas.x.thedream.cc/ROXCN-APP/roxhw/cdn/korea  # NAS路径"
    echo ""
}

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

# 设置基础目录和输出文件
BASE_DIR="${1:-.}"
OUTPUT_JSON="${2:-dir_update_time.json}"

echo "=========================================="
echo "目录更新时间列表"
echo "=========================================="
echo "基础目录: $BASE_DIR"
echo "输出文件: $OUTPUT_JSON"
echo ""

# 定义要搜索的根目录（不区分大小写）
ROOT_DIRS=("windows" "Windows" "ios" "IOS" "android" "Android")

# 存储结果的数组
declare -a RESULTS=()

# 获取目录下所有文件的最新修改时间
# 参数: $1 - 目录路径
# 返回: 最新修改时间的时间戳
get_latest_mtime() {
    local dir_path="$1"
    local latest_time=0
    
    # 方法1: 尝试使用 find -printf (GNU find)
    if find "$dir_path" -maxdepth 0 -printf '%T@\n' &>/dev/null; then
        while IFS= read -r mtime; do
            if [ -n "$mtime" ] && [ "${mtime%.*}" -gt "${latest_time%.*}" ] 2>/dev/null; then
                latest_time=$mtime
            fi
        done < <(find "$dir_path" -type f -printf '%T@\n' 2>/dev/null)
    else
        # 方法2: 使用 stat 命令 (macOS/BSD 兼容)
        while IFS= read -r file; do
            if [ -n "$file" ] && [ -f "$file" ]; then
                # 尝试 GNU stat 格式
                local mtime=$(stat -c '%Y' "$file" 2>/dev/null)
                # 如果失败，尝试 BSD/macOS stat 格式
                if [ -z "$mtime" ]; then
                    mtime=$(stat -f '%m' "$file" 2>/dev/null)
                fi
                if [ -n "$mtime" ] && [ "$mtime" -gt "$latest_time" ] 2>/dev/null; then
                    latest_time=$mtime
                fi
            fi
        done < <(find "$dir_path" -type f 2>/dev/null)
    fi
    
    # 方法3: 如果上面都失败，尝试使用 ls 获取目录本身的修改时间
    if [ "$latest_time" = "0" ]; then
        # 使用 GNU stat
        latest_time=$(stat -c '%Y' "$dir_path" 2>/dev/null)
        # 如果失败，尝试 BSD/macOS stat
        if [ -z "$latest_time" ]; then
            latest_time=$(stat -f '%m' "$dir_path" 2>/dev/null)
        fi
        # 如果还是失败，设为0
        if [ -z "$latest_time" ]; then
            latest_time=0
        fi
    fi
    
    echo "$latest_time"
}

# 格式化时间戳为可读格式
# 参数: $1 - 时间戳
format_time() {
    local timestamp="$1"
    if [ "$timestamp" = "0" ] || [ -z "$timestamp" ]; then
        echo "无文件"
    else
        # 转换为整数（去掉小数部分）
        local int_timestamp=${timestamp%.*}
        # 尝试 GNU date 格式
        local result=$(date -d "@$int_timestamp" "+%Y-%m-%d %H:%M:%S" 2>/dev/null)
        # 如果失败，尝试 BSD/macOS date 格式
        if [ -z "$result" ]; then
            result=$(date -r "$int_timestamp" "+%Y-%m-%d %H:%M:%S" 2>/dev/null)
        fi
        if [ -z "$result" ]; then
            echo "未知"
        else
            echo "$result"
        fi
    fi
}

# 计算目录大小
# 参数: $1 - 目录路径
get_dir_size() {
    local dir_path="$1"
    du -sh "$dir_path" 2>/dev/null | cut -f1 || echo "未知"
}

# 遍历每个根目录
for root_name in "${ROOT_DIRS[@]}"; do
    root_dir="$BASE_DIR/$root_name"
    
    if [ -d "$root_dir" ]; then
        echo "----------------------------------------"
        echo "平台: $root_name"
        echo "----------------------------------------"
        
        # 遍历第二级目录（如 eu_hgh, na_qa, gungho 等）
        for region_dir in "$root_dir"/*; do
            if [ -d "$region_dir" ]; then
                region_name=$(basename "$region_dir")
                
                # 遍历第三级目录（版本号目录，如 1.0, 1.1, 2.0 等）
                for version_dir in "$region_dir"/*; do
                    if [ -d "$version_dir" ]; then
                        version_name=$(basename "$version_dir")
                        
                        # 获取该版本目录下所有文件的最新修改时间
                        latest_mtime=$(get_latest_mtime "$version_dir")
                        formatted_time=$(format_time "$latest_mtime")
                        
                        # 获取目录大小
                        dir_size=$(get_dir_size "$version_dir")
                        
                        # 构建相对路径
                        relative_path="$root_name/$region_name/$version_name"
                        
                        # 存储结果（时间戳|路径|格式化时间|大小）
                        RESULTS+=("$latest_mtime|$relative_path|$formatted_time|$dir_size")
                        
                        echo "  $region_name/$version_name"
                        echo "    最后更新: $formatted_time"
                        echo "    目录大小: $dir_size"
                    fi
                done
            fi
        done
        echo ""
    fi
done

# 按时间排序输出汇总
echo ""
echo "=========================================="
echo "按更新时间排序（从旧到新）"
echo "=========================================="
echo ""

if [ ${#RESULTS[@]} -eq 0 ]; then
    echo "没有找到任何目录"
    exit 0
fi

# 排序并输出
printf '%s\n' "${RESULTS[@]}" | sort -t'|' -k1 -n | while IFS='|' read -r timestamp path formatted_time size; do
    if [ -n "$path" ]; then
        printf "%-50s | %-20s | %s\n" "$path" "$formatted_time" "$size"
    fi
done

echo ""
echo "=========================================="
echo "统计信息"
echo "=========================================="
echo "总共找到 ${#RESULTS[@]} 个版本目录"

# 找出最旧和最新的目录
oldest=$(printf '%s\n' "${RESULTS[@]}" | sort -t'|' -k1 -n | head -1)
newest=$(printf '%s\n' "${RESULTS[@]}" | sort -t'|' -k1 -rn | head -1)

if [ -n "$oldest" ]; then
    oldest_path=$(echo "$oldest" | cut -d'|' -f2)
    oldest_time=$(echo "$oldest" | cut -d'|' -f3)
    echo "最旧目录: $oldest_path ($oldest_time)"
fi

if [ -n "$newest" ]; then
    newest_path=$(echo "$newest" | cut -d'|' -f2)
    newest_time=$(echo "$newest" | cut -d'|' -f3)
    echo "最新目录: $newest_path ($newest_time)"
fi

# 生成 JSON 文件
echo ""
echo "=========================================="
echo "生成 JSON 文件"
echo "=========================================="

# 获取当前时间
CURRENT_TIME=$(date "+%Y-%m-%d %H:%M:%S" 2>/dev/null || date "+%Y-%m-%d %H:%M:%S")

# 开始写入 JSON
{
    echo "{"
    echo "  \"generated_at\": \"$CURRENT_TIME\","
    echo "  \"base_dir\": \"$BASE_DIR\","
    echo "  \"total_count\": ${#RESULTS[@]},"
    
    # 统计信息
    if [ -n "$oldest" ]; then
        echo "  \"oldest\": {"
        echo "    \"path\": \"$oldest_path\","
        echo "    \"time\": \"$oldest_time\""
        echo "  },"
    fi
    if [ -n "$newest" ]; then
        echo "  \"newest\": {"
        echo "    \"path\": \"$newest_path\","
        echo "    \"time\": \"$newest_time\""
        echo "  },"
    fi
    
    echo "  \"directories\": ["
    
    # 按时间排序输出每个目录
    local first=true
    printf '%s\n' "${RESULTS[@]}" | sort -t'|' -k1 -n | while IFS='|' read -r timestamp path formatted_time size; do
        if [ -n "$path" ]; then
            # 解析路径获取平台、区域、版本
            platform=$(echo "$path" | cut -d'/' -f1)
            region=$(echo "$path" | cut -d'/' -f2)
            version=$(echo "$path" | cut -d'/' -f3)
            
            # 去掉大小中的空格
            size=$(echo "$size" | tr -d ' ')
            
            # 转换时间戳为整数
            int_timestamp=${timestamp%.*}
            
            if [ "$first" = true ]; then
                first=false
            else
                echo ","
            fi
            
            printf "    {\n"
            printf "      \"path\": \"%s\",\n" "$path"
            printf "      \"platform\": \"%s\",\n" "$platform"
            printf "      \"region\": \"%s\",\n" "$region"
            printf "      \"version\": \"%s\",\n" "$version"
            printf "      \"timestamp\": %s,\n" "${int_timestamp:-0}"
            printf "      \"update_time\": \"%s\",\n" "$formatted_time"
            printf "      \"size\": \"%s\"\n" "$size"
            printf "    }"
        fi
    done
    
    echo ""
    echo "  ]"
    echo "}"
} > "$OUTPUT_JSON"

echo "JSON 文件已保存到: $OUTPUT_JSON"
echo ""

# 显示 JSON 文件内容预览
echo "文件内容预览:"
head -30 "$OUTPUT_JSON"
if [ $(wc -l < "$OUTPUT_JSON") -gt 30 ]; then
    echo "... (共 $(wc -l < "$OUTPUT_JSON") 行)"
fi
