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

require_env() {
  local name="$1"
  if [[ -z "${!name:-}" ]]; then
    echo "missing required environment variable: ${name}" >&2
    return 1
  fi
}

require_file_or_env() {
  local file_name="$1"
  local env_name="$2"
  if [[ -n "${!file_name:-}" && -f "${!file_name:-}" ]]; then
    return 0
  fi
  if [[ -n "${!env_name:-}" ]]; then
    return 0
  fi
  echo "missing required ${file_name} file or ${env_name} environment value" >&2
  return 1
}

case "${1:-all}" in
  gcs)
    require_env BURROW_GOOGLE_PROJECT_ID
    require_env BURROW_GOOGLE_PROJECT_NUMBER
    require_env BURROW_GOOGLE_WIF_POOL_ID
    require_env BURROW_GOOGLE_WIF_PROVIDER_ID
    require_env BURROW_GOOGLE_WIF_SERVICE_ACCOUNT
    require_env BURROW_AUTHENTIK_WIF_ISSUER
    require_env BURROW_AUTHENTIK_WIF_AUDIENCE
    require_env BURROW_AUTHENTIK_WIF_CLIENT_ID
    if [[ -z "${BURROW_AUTHENTIK_WIF_TOKEN:-}" && -z "${BURROW_AUTHENTIK_WIF_CLIENT_SECRET:-}" ]]; then
      if [[ -z "${BURROW_AUTHENTIK_WIF_TOKEN_FILE:-}" || ! -f "${BURROW_AUTHENTIK_WIF_TOKEN_FILE:-}" ]]; then
        echo "missing Authentik WIF token, token file, or client secret" >&2
        exit 1
      fi
    fi
    ;;
  app-store)
    require_env ASC_API_KEY_ID
    require_env ASC_API_ISSUER_ID
    require_file_or_env ASC_API_KEY_PATH ASC_API_KEY_BASE64
    ;;
  apple-signing)
    require_file_or_env APPLE_SIGNING_CERTIFICATE_PATH APPLE_SIGNING_CERTIFICATE_BASE64
    require_env APPLE_SIGNING_CERTIFICATE_PASSWORD
    ;;
  sparkle)
    "$0" gcs
    ;;
  microsoft-store)
    require_env MICROSOFT_TENANT_ID
    require_env MICROSOFT_CLIENT_ID
    require_env MICROSOFT_CLIENT_SECRET
    ;;
  all)
    "$0" gcs
    "$0" app-store
    "$0" apple-signing
    ;;
  *)
    echo "unknown release config group: $1" >&2
    exit 64
    ;;
esac
