#!/bin/bash
# Serve a static tree through the host Caddy service.
# Written by orbit init. Edit this file. Re-run init with --force to replace it.
set -euo pipefail

: "${SLOT_NAME:?}"
: "${SLOT_SRC:?}"
: "${SLOT_RUN:?}"
: "${ORBIT_CADDY:?}"
: "${SLOT_TTL:=0}"

HOSTS=${SLOT_CADDY_HOSTS:-$SLOT_NAME}
STATIC_ROOT=@@STATIC_ROOT@@
PREVIEW_BASIC_AUTH=${PREVIEW_BASIC_AUTH:-1}
BASIC_AUTH_USER=
BASIC_AUTH_HASH=

if [[ $STATIC_ROOT == . ]]; then
    ROOT=$SLOT_SRC
else
    ROOT=$SLOT_SRC/$STATIC_ROOT
fi

ensure_preview_auth() {
    BASIC_AUTH_USER=
    BASIC_AUTH_HASH=
    [[ $PREVIEW_BASIC_AUTH == 1 ]] || return 0
    [[ $SLOT_TTL =~ ^[1-9][0-9]*$ ]] || return 0
    local hash_file=$SLOT_RUN/basic_auth.hash
    if [[ -f $hash_file ]]; then
        BASIC_AUTH_USER=orbit
        BASIC_AUTH_HASH=$(<"$hash_file")
        BASIC_AUTH_HASH=${BASIC_AUTH_HASH//$'\n'/}
        return 0
    fi
    local password
    password=$(openssl rand -base64 24 | tr -d '\n/=+' | head -c 24)
    [[ -n $password ]] || {
        echo "[error] failed to generate preview password"
        exit 1
    }
    BASIC_AUTH_HASH=$(caddy hash-password --plaintext "$password") || {
        echo "[error] caddy hash-password failed"
        exit 1
    }
    install -m 0600 /dev/null "$hash_file"
    printf '%s\n' "$BASIC_AUTH_HASH" >"$hash_file"
    BASIC_AUTH_USER=orbit
    echo "[auth] preview basic auth user=orbit password=$password"
}

for command_name in caddy openssl; do
    command -v "$command_name" >/dev/null 2>&1 || {
        echo "[error] need $command_name in PATH"
        exit 1
    }
done

[[ -d $ROOT ]] || {
    echo "[error] static root missing: $ROOT"
    exit 1
}

ensure_preview_auth
mkdir -p "$SLOT_RUN"

{
    printf '%s {\n' "${HOSTS//,/ }"
    if [[ -n $BASIC_AUTH_HASH ]]; then
        printf '\tbasic_auth {\n'
        printf '\t\t%s %s\n' "$BASIC_AUTH_USER" "$BASIC_AUTH_HASH"
        printf '\t}\n'
    fi
    printf '\troot * %s\n' "$ROOT"
    printf '\tfile_server\n}\n'
} >"${SLOT_RUN}/Caddyfile"

caddy fmt --overwrite "${SLOT_RUN}/Caddyfile"
caddy fmt --overwrite "$ORBIT_CADDY"
caddy validate --config "$ORBIT_CADDY"
caddy reload --config "$ORBIT_CADDY"
echo "[done] static $HOSTS root=$ROOT"
