#!/bin/bash
# entrypoint-gateway.sh – start-up script for the cvmfs-gateway container.
#
# 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` to initialise the Stratum-0 repository.
#   5. Writes an Apache ProxyPass snippet to the shared /apache-conf volume so
#      the Apache container can serve the repository from Garage.
# On every subsequent boot it skips straight to starting cvmfs_gateway.

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}"
# URL advertised to CVMFS clients (and used to verify the repo is reachable)
STRATUM0_URL="${STRATUM0_URL:-http://cvmfs-apache}"
# 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"
APACHE_CONF_DIR="/apache-conf"
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 -sf --max-time 3 "http://${GARAGE_HOST}:${GARAGE_S3_PORT}" > /dev/null 2>&1 || \
      curl -sf --max-time 3 "http://${GARAGE_HOST}:${GARAGE_S3_PORT}/health" > /dev/null 2>&1; do
    sleep 2
done
echo "[entrypoint-gateway] Garage S3 is up."

# ---------------------------------------------------------------------------
# 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
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.
    # -s  path to the S3 config file
    # -w  HTTP base URL from which clients download the repo (Apache frontend)
    # -o  owning user
    # overlayfs is required; the container must be run with --privileged.
    echo "[entrypoint-gateway] Running cvmfs_server mkfs ..."
    cvmfs_server mkfs \
        -s "${S3_CONFIG_FILE}" \
        -w "${STRATUM0_URL}/cvmfs" \
        -o "${REPO_OWNER}" \
        -f overlayfs \
        "${REPO_NAME}"
    echo "[entrypoint-gateway] cvmfs_server mkfs complete."

    # ---------------------------------------------------------------------------
    # 5. Write Apache ProxyPass config to the shared volume so the Apache
    #    container can start serving the repository.
    #    With S3 upstream, cvmfs_server does NOT auto-generate an Apache config,
    #    so we create one that proxies /cvmfs/<repo> → Garage S3.
    # ---------------------------------------------------------------------------
    mkdir -p "${APACHE_CONF_DIR}"
    cat > "${APACHE_CONF_DIR}/cvmfs_${REPO_NAME}.conf" <<APACHEEOF
# Generated by entrypoint-gateway.sh for ${REPO_NAME}
KeepAlive On
AddType application/json .json

<FilesMatch "^\\.cvmfs">
    ForceType application/x-cvmfs
</FilesMatch>

# ProxyPass: forward /cvmfs/<repo> requests to the Garage S3 bucket path
# Objects are stored under s3://${S3_BUCKET}/${REPO_NAME}/<hash>
ProxyPass        /cvmfs/${REPO_NAME} http://${GARAGE_HOST}:${GARAGE_S3_PORT}/${S3_BUCKET}/${REPO_NAME}
ProxyPassReverse /cvmfs/${REPO_NAME} http://${GARAGE_HOST}:${GARAGE_S3_PORT}/${S3_BUCKET}/${REPO_NAME}
APACHEEOF
    echo "[entrypoint-gateway] Apache config written to ${APACHE_CONF_DIR}/cvmfs_${REPO_NAME}.conf."

    touch "${SETUP_DONE_MARKER}"
fi

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

