#!/usr/bin/env bash
# One-time Azure setup for SOT Demo v2 static hosting (Blob Storage static website).
set -euo pipefail

RESOURCE_GROUP="${RESOURCE_GROUP:-sot-demo-rg}"
LOCATION="${LOCATION:-uaenorth}"
STORAGE_ACCOUNT="${STORAGE_ACCOUNT:-}"

usage() {
  cat <<'EOF'
Usage: STORAGE_ACCOUNT=<unique-name> ./infra/azure/provision.sh

Creates (or updates) a resource group and deploys infra/azure/static-web.bicep.

Examples:
  STORAGE_ACCOUNT=sotdemov2prod ./infra/azure/provision.sh
  RESOURCE_GROUP=sot-demo-rg LOCATION=uaenorth STORAGE_ACCOUNT=sotdemov2 ./infra/azure/provision.sh

After deploy, grant the Azure DevOps service principal "Storage Blob Data Contributor"
on this storage account (or use the account key in a secret pipeline variable).
EOF
}

if [[ -z "${STORAGE_ACCOUNT}" ]]; then
  usage
  exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo "==> Ensuring resource group: ${RESOURCE_GROUP} (${LOCATION})"
az group create --name "${RESOURCE_GROUP}" --location "${LOCATION}" --output none

echo "==> Deploying static website storage"
DEPLOYMENT_OUTPUT="$(
  az deployment group create \
    --resource-group "${RESOURCE_GROUP}" \
    --template-file "${SCRIPT_DIR}/static-web.bicep" \
    --parameters storageAccountName="${STORAGE_ACCOUNT}" \
    --query properties.outputs \
    --output json
)"

echo "${DEPLOYMENT_OUTPUT}" | jq .

WEB_URL="$(echo "${DEPLOYMENT_OUTPUT}" | jq -r '.staticWebsiteUrl.value')"
echo ""
echo "Static website URL: ${WEB_URL}"
echo ""
echo "Next: configure Azure DevOps pipeline variables (see infra/azure/README.md)."
