#! /bin/sh
set -e

# Check if VERCEL_TOKEN is set
if [ -z "$VERCEL_TOKEN" ]; then
  echo "Error: VERCEL_TOKEN is not set."
  exit 1
fi

# Check if VERCEL_PROJECT_ID is set
if [ -z "$VERCEL_PROJECT_ID" ]; then
  echo "Error: VERCEL_PROJECT_ID is not set."
  exit 1
fi

# Check if VERCEL_ORG_ID is set
if [ -z "$VERCEL_ORG_ID" ]; then
  echo "Error: VERCEL_ORG_ID is not set."
  exit 1
fi

# Deploy to Vercel with extra arguments
DEPLOY_URL=$(yarn --silent vercel deploy --force --token "$VERCEL_TOKEN" "$@")

echo "Deployment URL: $DEPLOY_URL"

# Check if deployment was successful
if [ $? -ne 0 ]; then
  echo "Deployment failed."
  exit 1
fi

# If VERCEL_DOMAIN is set, alias the deployment to the domains
if [ -n "$DOMAINS" ]; then
  for domain in $DOMAINS; do
    echo "Assigning deployment domain: $domain"
    yarn vercel alias "$DEPLOY_URL" "$domain" --token "$VERCEL_TOKEN"
  done
fi

echo "Deployment successful."