#!/bin/bash
# entrypoint-gateway.sh – start-up script for the cvmfs-gateway container.
#
# This container runs in MOUNTLESS mode (no FUSE, no overlayfs, no privileged).
#
# On first boot it:
#   1. Waits for Garage S3 to accept connections.
#   2. Writes the per-repo S3 config file read by cvmfs_server / cvmfs_receiver.
#   3. Writes the gateway key file for the repository.
#   4. Runs `cvmfs_server mkfs -P -D` to initialise the Stratum-0 repository
#      without mounting a FUSE publisher view.  -D publishes client setup
#      (public key + mount helper script) to the storage backend.
# On every subsequent boot it skips straight to starting cvmfs_gateway.
#
# CVMFS clients read repository data directly from Garage's built-in web
# endpoint (s3_web).  No Apache/httpd reverse proxy is needed.
#
# Publishing into this repository is done from a separate publisher
# container that connects via `cvmfs_server connect-gw -P`.

set -e

# ---------------------------------------------------------------------------
# Configurable via environment variables (docker-compose env_file / environment)
# ---------------------------------------------------------------------------
REPO_NAME="${REPO_NAME:-test.repo.org}"
REPO_OWNER="${REPO_OWNER:-root}"
GARAGE_HOST="${GARAGE_HOST:-cvmfs-garage}"
GARAGE_S3_PORT="${GARAGE_S3_PORT:-3900}"
S3_BUCKET="${S3_BUCKET:-cvmfs}"
S3_ACCESS_KEY="${S3_ACCESS_KEY:-GKcvmfsaccesskey00000001}"
S3_SECRET_KEY="${S3_SECRET_KEY:-cvmfs_secret_key_placeholder_32chars}"
# Stratum-0 URL: Garage's web endpoint, reachable via the Docker network alias
# that matches the <bucket>.web.garage.localhost pattern.
STRATUM0_URL="${STRATUM0_URL:-http://cvmfs.web.garage.internal:3902}"
# Gateway lease key written to /etc/cvmfs/keys/<repo>.gw
GW_KEY_ID="${GW_KEY_ID:-mykey}"
GW_KEY_SECRET="${GW_KEY_SECRET:-mysecret}"

S3_CONFIG_DIR="/etc/cvmfs/s3config"
S3_CONFIG_FILE="${S3_CONFIG_DIR}/${REPO_NAME}.cfg"
GW_KEY_FILE="/etc/cvmfs/keys/${REPO_NAME}.gw"
SETUP_DONE_MARKER="/var/lib/cvmfs-gateway/.setup_done"

# ---------------------------------------------------------------------------
# 1. Wait for Garage S3 endpoint
# ---------------------------------------------------------------------------
echo "[entrypoint-gateway] Waiting for Garage S3 at ${GARAGE_HOST}:${GARAGE_S3_PORT} ..."
until curl -s --max-time 3 -o /dev/null -w '%{http_code}' "http://${GARAGE_HOST}:${GARAGE_S3_PORT}" 2>/dev/null | grep -qE '^[2-4]'; do
    sleep 2
done
echo "[entrypoint-gateway] Garage S3 is up."

# Wait for the S3 key/bucket to be ready (garage-setup may still be running).
# Poll the Garage admin API to check that the bucket exists.
GARAGE_ADMIN_URL="http://${GARAGE_HOST}:3903"
GARAGE_ADMIN_TOKEN="${GARAGE_ADMIN_TOKEN:-garage-admin-token}"
echo "[entrypoint-gateway] Waiting for S3 bucket '${S3_BUCKET}' to exist ..."
until curl -s --max-time 3 -H "Authorization: Bearer ${GARAGE_ADMIN_TOKEN}" \
    "${GARAGE_ADMIN_URL}/v2/ListBuckets" 2>/dev/null | grep -q "${S3_BUCKET}"; do
    sleep 2
done
echo "[entrypoint-gateway] S3 bucket '${S3_BUCKET}' exists."

# ---------------------------------------------------------------------------
# 2. Write S3 config (always refresh so credential changes take effect)
# ---------------------------------------------------------------------------
mkdir -p "${S3_CONFIG_DIR}"
cat > "${S3_CONFIG_FILE}" <<EOF
# Generated by entrypoint-gateway.sh – do not edit manually.
CVMFS_S3_HOST=${GARAGE_HOST}:${GARAGE_S3_PORT}
CVMFS_S3_ACCESS_KEY=${S3_ACCESS_KEY}
CVMFS_S3_SECRET_KEY=${S3_SECRET_KEY}
CVMFS_S3_BUCKET=${S3_BUCKET}
# Use path-style S3 URLs (required for Garage with no DNS wildcard)
CVMFS_S3_DNS_BUCKETS=false
CVMFS_S3_MAX_NUMBER_OF_PARALLEL_CONNECTIONS=10
# Garage v2 only supports AWS Signature V4
CVMFS_S3_FLAVOR=awsv4
CVMFS_S3_REGION=garage
EOF
echo "[entrypoint-gateway] S3 config written to ${S3_CONFIG_FILE}."

# ---------------------------------------------------------------------------
# 3 + 4. First-boot repository initialisation
# ---------------------------------------------------------------------------
if [ ! -f "${SETUP_DONE_MARKER}" ]; then
    echo "[entrypoint-gateway] First boot – initialising repository ${REPO_NAME}."

    # Write gateway lease key
    mkdir -p "$(dirname "${GW_KEY_FILE}")"
    echo "plain_text ${GW_KEY_ID} ${GW_KEY_SECRET}" > "${GW_KEY_FILE}"
    echo "[entrypoint-gateway] Gateway key written to ${GW_KEY_FILE}."

    # Create the Stratum-0 repository with S3 upstream in mountless mode.
    # -P  mountless publisher: skip FUSE mount (no overlayfs, no privileged)
    # -p  skip Apache configuration (no Apache in this stack)
    # -f  union-fs type: overlayfs is recorded in config but never mounted
    #     (avoids get_available_union_fs trying modprobe in a container)
    # -s  path to the S3 config file
    # -w  HTTP base URL from which clients download the repo
    #     Points directly at Garage's web endpoint; mangle_s3_cvmfs_url
    #     will append /<repo_name> automatically.
    # -o  owning user
    echo "[entrypoint-gateway] Running cvmfs_server mkfs -P -D (mountless) ..."
    echo "[entrypoint-gateway] Stratum-0 URL: ${STRATUM0_URL}"
    cvmfs_server mkfs \
        -P \
        -D \
        -p \
        -f overlayfs \
        -s "${S3_CONFIG_FILE}" \
        -w "${STRATUM0_URL}" \
        -o "${REPO_OWNER}" \
        "${REPO_NAME}"
    echo "[entrypoint-gateway] cvmfs_server mkfs -P -D complete (no FUSE mount)."

    touch "${SETUP_DONE_MARKER}"
fi

# ---------------------------------------------------------------------------
# Start the gateway
# ---------------------------------------------------------------------------
echo "[entrypoint-gateway] Starting cvmfs_gateway ..."
exec /usr/bin/cvmfs_gateway
