#!/bin/sh
set -e

echo "[minio-init] Configuring alias..."
mc alias set local http://minio:9000 "$MINIO_ROOT_USER" "$MINIO_ROOT_PASSWORD"

if mc ls local/mineseeker > /dev/null 2>&1; then
    echo "[minio-init] Already initialized, skipping."
    exit 0
fi

echo "[minio-init] Creating bucket 'mineseeker'..."
mc mb local/mineseeker

echo "[minio-init] Creating directories..."
echo '' | mc pipe local/mineseeker/media/.keep
echo '' | mc pipe local/mineseeker/cache/.keep

echo "[minio-init] Applying anonymous read policy for media/ and cache/..."
printf '%s' '{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "AWS": ["*"] },
      "Action": ["s3:GetObject"],
      "Resource": [
        "arn:aws:s3:::mineseeker/media/*",
        "arn:aws:s3:::mineseeker/cache/*"
      ]
    }
  ]
}' > /tmp/policy.json
mc anonymous set-json /tmp/policy.json local/mineseeker

echo "[minio-init] Done."
