#!/bin/sh
# MinIO Bucket 初始化脚本
# 在 MinIO 启动后执行，创建必要的 bucket 和策略

set -e

# 等待 MinIO 启动
echo "Waiting for MinIO to start..."
until mc alias set myminio http://minio:9000 ${MINIO_ROOT_USER} ${MINIO_ROOT_PASSWORD} > /dev/null 2>&1; do
  echo "MinIO is unavailable - sleeping"
  sleep 2
done

echo "MinIO is up - creating buckets"

# 创建主 bucket
mc mb --ignore-existing myminio/iconsulting

# 设置 bucket 策略为私有
mc anonymous set none myminio/iconsulting

# 创建目录结构（通过创建空对象）
echo "Creating directory structure..."

# uploads 目录
mc cp /dev/null myminio/iconsulting/uploads/images/.keep 2>/dev/null || true
mc cp /dev/null myminio/iconsulting/uploads/documents/.keep 2>/dev/null || true
mc cp /dev/null myminio/iconsulting/uploads/temp/.keep 2>/dev/null || true

# processed 目录
mc cp /dev/null myminio/iconsulting/processed/thumbnails/.keep 2>/dev/null || true
mc cp /dev/null myminio/iconsulting/processed/extracted/.keep 2>/dev/null || true

# exports 目录
mc cp /dev/null myminio/iconsulting/exports/.keep 2>/dev/null || true

# 设置生命周期规则 - temp 目录 24小时后删除
echo "Setting lifecycle rules..."
cat > /tmp/lifecycle.json << 'EOF'
{
  "Rules": [
    {
      "ID": "temp-cleanup",
      "Status": "Enabled",
      "Filter": {
        "Prefix": "uploads/temp/"
      },
      "Expiration": {
        "Days": 1
      }
    },
    {
      "ID": "thumbnails-cleanup",
      "Status": "Enabled",
      "Filter": {
        "Prefix": "processed/thumbnails/"
      },
      "Expiration": {
        "Days": 30
      }
    }
  ]
}
EOF

mc ilm import myminio/iconsulting < /tmp/lifecycle.json || echo "Lifecycle rules may already exist"

echo "MinIO initialization completed!"
echo "Bucket: iconsulting"
echo "API: http://minio:9000"
echo "Console: http://minio:9001"
