#!/usr/bin/env bash

set -euo pipefail

AZURITE_DIR="${AZURITE_DIR:-}"
CONTAINER_ARGS=()
AZURITE_IMAGE="${AZURITE_IMAGE:-azurite:latest}"

while [[ $# -gt 0 ]]; do
    case "$1" in
        --no-oauth|--no-caddy)
            # Pass these flags to the container, so that it can configure Azurite accordingly.
            CONTAINER_ARGS+=("$1")
            shift
            ;;
        -d|--azurite-dir)
            if [[ -n "$2" && -d "$2" ]]; then
                AZURITE_DIR="$2"
                shift 2
            else
                echo "Error: Selected directory does not exist." >&2
                exit 1
            fi
            ;;
        *)
            echo "Error: Unknown argument: $1" >&2
            exit 1
            ;;
    esac
done

# Check, if the AZURITE_DIR variable is set and is a valid directory
if [[ -z "$AZURITE_DIR" || ! -d "$AZURITE_DIR" ]]; then
    echo "Error: AZURITE_DIR is not set or is not a valid directory." >&2
    exit 1
fi

# Check, if the accounts.env file exists in the AZURITE_DIR directory
if [[ ! -f "$AZURITE_DIR/accounts.env" ]]; then
    echo "Error: accounts.env file not found in AZURITE_DIR directory." >&2
    exit 1
fi

source "$AZURITE_DIR/accounts.env"
if [[ -z "$AZURITE_ACCOUNTS" ]]; then
    echo "Error: AZURITE_ACCOUNTS variable is not set in accounts.env file." >&2
    exit 1
fi

ACCOUNT_NAME=$(echo "$AZURITE_ACCOUNTS" | cut -f 1 -d ';' | cut -f 1 -d ':')

# Check, if the certificate for the account exists.
if [[ ! -f "$AZURITE_DIR/storage/${ACCOUNT_NAME}_cert.pem" ]] || [[ ! -f "$AZURITE_DIR/storage/${ACCOUNT_NAME}_key.pem" ]]; then
    echo "Error: Certificate or key for account ${ACCOUNT_NAME} not found in AZURITE_DIR directory." >&2
    exit 1
fi

if command -v docker &> /dev/null; then
    docker run \
        --rm \
        -d \
        --name azurite \
        --env-file "$AZURITE_DIR/accounts.env" \
        -p 443:443 \
        -v "$AZURITE_DIR/storage":/storage \
        "$AZURITE_IMAGE" "${CONTAINER_ARGS[@]}"
elif command -v container &> /dev/null; then
    container run \
        -c 2 \
        -m 512M \
        --rm \
        -d \
        --name azurite \
        --env-file "$AZURITE_DIR/accounts.env" \
        -p 443:443 \
        --mount type=bind,source="$AZURITE_DIR/storage",target=/storage \
        "$AZURITE_IMAGE" "${CONTAINER_ARGS[@]}"
else
    echo "Neither supported container runtime found." >&2
    exit 1
fi
