#!/bin/bash

# 1. Look for the .env file in the periphery folder we standardized
ENV_PATH="/docker/minio/.env"

if [ -f "$ENV_PATH" ]; then
    while read -r line || [ -n "$line" ]; do
        # Skip comments and empty lines
        [[ "$line" =~ ^#.*$ ]] && continue
        [[ -z "$line" ]] && continue
        
        # Export the variable, removing any literal quotes
        export "${line//\"/}"
    done < "$ENV_PATH"
    echo "Successfully loaded variables from $ENV_PATH"
else
    echo "ERROR: Could not find .env at $ENV_PATH"
    exit 1
fi

# 2. Now use the variables that were just loaded
NODE_NUM="${MINIO_NODE_NUMBER}"
BUCKET_LIST="${MINIO_BUCKET_REGISTRY}"
DATA_PATH="/docker/minio/data"

if [ -z "$NODE_NUM" ]; then
    echo "ERROR: MINIO_NODE_NUMBER not found in .env"
    exit 1
fi

CONTAINER_NAME="minio-node${NODE_NUM}"

echo "--- S3 Provisioning Started for ${CONTAINER_NAME} ---"
docker stop "${CONTAINER_NAME}" 2>/dev/null || true
sleep 2

for BUCKET in $BUCKET_LIST; do
    TARGET_DIR="$DATA_PATH/$BUCKET"
    if [ ! -d "$TARGET_DIR" ]; then
        echo "NEW: Creating $BUCKET"
        mkdir -p "$TARGET_DIR"
        chown -R 1000:1000 "$TARGET_DIR"
    fi
done

docker start "${CONTAINER_NAME}"
echo "--- Provisioning Complete ---"