#!/bin/sh
# Start MinIO and pre-create the backup bucket.
#
# celilo's S3 provider never creates buckets (its initialize() only probes via
# ListObjectsV2), so the bucket must exist before `storage add s3` verifies or
# `backup --storage` uploads. We start the server, wait for it to answer, then
# `mc mb --ignore-existing`.
set -e

# Route the customer's public prefix via the ISP edge (fw-ext), like every
# other host on internet-external. Docker's default bridge gateway has no path
# across networks, so without this a reply to the customer's WAN address is
# dropped and `backup --storage` hangs. fw-ext is per-test, so this is
# expected to fail while shared infra runs alone — hence the tolerance.
# (`busybox ip` because the MinIO image ships no iproute2.)
busybox ip route del default 2>/dev/null || true
busybox ip route add default via 100.64.0.1 2>/dev/null || true

# Serve the S3 API on :80 so the management box reaches it over the SAME
# proven HTTP egress path as the other public sims (apt-repo, npm-registry):
# fw-ext's Squid-bypass exception is scoped to dport 80/443 → 100.64.0.0/24, so
# plain HTTP to minio.lab:80 forwards straight through (no TLS bump, no cert,
# no nonstandard-port filtering). Console stays on :9001.
minio server /data --address ":80" --console-address ":9001" &
MINIO_PID=$!

# Wait for the server to accept the admin alias (up to ~30s).
ready=0
i=0
while [ "$i" -lt 30 ]; do
  if mc alias set local "http://127.0.0.1:80" "$MINIO_ROOT_USER" "$MINIO_ROOT_PASSWORD" >/dev/null 2>&1; then
    ready=1
    break
  fi
  i=$((i + 1))
  sleep 1
done

if [ "$ready" -ne 1 ]; then
  echo "minio-startup: MinIO did not become ready in 30s" >&2
  exit 1
fi

mc mb --ignore-existing "local/${MINIO_BUCKET}"
echo "minio-startup: bucket '${MINIO_BUCKET}' ready; MinIO serving on :80"

# Hand the foreground back to the server so the container stays up and signals
# propagate to it.
wait "$MINIO_PID"
