#!/usr/bin/env bash
set -eo pipefail

if [[ -z "$AZURE_STORAGE_CONNECTION_STRING" ]]; then
    echo "AZURE_STORAGE_CONNECTION_STRING is required"
    exit 1
fi

if [[ -z "$CONTAINER_NAME" ]]; then
    echo "CONTAINER_NAME is required"
    exit 1
fi

if [[ -z "$BLOB_NAME" ]] && [[ -z "$BLOB_PREFIX" ]]; then
    echo "one of BLOB_NAME or BLOB_PREFIX is required"
    exit 1
fi

DEFAULT_ARGS=(--connection-string "$AZURE_STORAGE_CONNECTION_STRING")

if [[ -z "$BLOB_PREFIX" ]]; then
    if [[ "$(az storage blob exists "${DEFAULT_ARGS[@]}" --output tsv)" = True ]]; then
        echo "Deleting cache"
        az storage blob delete --container-name "$CONTAINER_NAME" "${DEFAULT_ARGS[@]}" --name "$BLOB_NAME"
    fi
else
    echo "Deleting cache"
    az storage blob delete-batch --source "$CONTAINER_NAME" "${DEFAULT_ARGS[@]}" --pattern "${BLOB_PREFIX}*"
fi
