#!/usr/bin/env ruby
#
#  Make sure the bucket we rely upon in development exists.
#  Configuration and credentials are in config/storage.yml
#
require_relative "../config/environment"
require "aws-sdk-s3"

# Load storage configuration
storage_config = YAML.load(ERB.new(File.read("config/storage.yml")).result)
minio_config = storage_config["devminio"]

bucket_name = minio_config["bucket"]
endpoint = minio_config["endpoint"]
access_key = minio_config["access_key_id"]
secret_key = minio_config["secret_access_key"]
region = minio_config["region"]

# Create S3 client
s3_client = Aws::S3::Client.new(
  endpoint: endpoint,
  access_key_id: access_key,
  secret_access_key: secret_key,
  region: region,
  force_path_style: minio_config["force_path_style"]
)

# Check if bucket exists
begin
  s3_client.head_bucket(bucket: bucket_name)
  puts "Bucket '#{bucket_name}' already exists"
rescue Aws::S3::Errors::NotFound
  # Create the bucket
  puts "Creating bucket '#{bucket_name}'..."
  s3_client.create_bucket(bucket: bucket_name)
  puts "Successfully created bucket '#{bucket_name}'"
rescue => e
  puts "Error checking/creating bucket: #{e.message}"
  exit 1
end
