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

ROOT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
ENVIRONMENT="${1:-staging}"
[[ "$ENVIRONMENT" == dev || "$ENVIRONMENT" == staging || "$ENVIRONMENT" == production || "$ENVIRONMENT" == prod ]] || {
  echo "usage: deploy-convex [dev|staging|production|prod] [convex deploy args...]" >&2
  exit 2
}
shift || true
FROM_CURRENT_ENV=0
if [[ "${1:-}" == "--from-current-env" ]]; then
  FROM_CURRENT_ENV=1
  shift
fi

ENV_FILE="${CI_ENV_FILE:-}"
cleanup() {
  [[ -n "$ENV_FILE" && "$ENV_FILE" != "${CI_ENV_FILE:-}" ]] && rm -f "$ENV_FILE" || true
}
trap cleanup EXIT

if [[ "$FROM_CURRENT_ENV" -eq 0 && -z "$ENV_FILE" && -z "${CI:-}" ]]; then
  ENV_FILE="$(mktemp "${TMPDIR:-/tmp}/spoon-convex-deploy.XXXXXX.env")"
  sh "$ROOT_DIR/scripts/export-env" "$ENVIRONMENT" > "$ENV_FILE"
fi

deploy_from_current_env() {
  if [[ -z "${CONVEX_SELF_HOSTED_URL:-}" ]]; then
    if [[ -n "${CONVEX_URL:-}" ]]; then
      export CONVEX_SELF_HOSTED_URL="$CONVEX_URL"
    elif [[ -n "${NEXT_PUBLIC_CONVEX_URL:-}" ]]; then
      export CONVEX_SELF_HOSTED_URL="$NEXT_PUBLIC_CONVEX_URL"
    fi
  fi

  bash "$ROOT_DIR/scripts/sync-convex-env" "$ENVIRONMENT" --from-current-env
  bash "$ROOT_DIR/scripts/convex-codegen"
  cd "$ROOT_DIR"
  bun patch:usesend
  cd "$ROOT_DIR/packages/backend"
  bun convex deploy --typecheck disable "$@"
}

if [[ "$FROM_CURRENT_ENV" -eq 0 && -n "$ENV_FILE" ]]; then
  exec bun dotenv -e "$ENV_FILE" -- bash "$0" "$ENVIRONMENT" --from-current-env "$@"
fi

deploy_from_current_env "$@"
