#!/bin/bash

set -euo pipefail

APP_NAME="${APP_NAME:?Set APP_NAME, for example frontend-my-app}"
DOMAIN="${DOMAIN:?Set DOMAIN, for example my-app.dev.theorchard.io}"
BUILD_DIR="${BUILD_DIR:-build}"
BUILD_TOOL="${BUILD_TOOL:-auto}"
ASSET_PREFIX="${ASSET_PREFIX:-$APP_NAME}"

echo "Building $APP_NAME for https://$DOMAIN"
export CDN_URL="https://$DOMAIN"
export VITE_API_BASE_URL="https://$DOMAIN"

if [ "$BUILD_TOOL" = "auto" ]; then
  if [ -f package.json ] && grep -q '"packageManager": "pnpm' package.json; then
    BUILD_TOOL="pnpm"
  else
    BUILD_TOOL="npm"
  fi
fi

case "$BUILD_TOOL" in
  pnpm) pnpm build ;;
  npm) npm run build ;;
  yarn) yarn build ;;
  *)
    echo "Unsupported BUILD_TOOL: $BUILD_TOOL" >&2
    exit 1
    ;;
esac

if [ ! -f "$BUILD_DIR/index.html" ]; then
  echo "Missing $BUILD_DIR/index.html" >&2
  exit 1
fi

echo "Uploading index.html to s3://$DOMAIN/index.html"
aws s3 cp "$BUILD_DIR/index.html" "s3://$DOMAIN/index.html"

echo "Uploading static assets to s3://$DOMAIN/$ASSET_PREFIX/"
find "$BUILD_DIR" -maxdepth 1 -type f \( -name '*.js' -o -name '*.css' -o -name '*.map' \) -print0 |
  while IFS= read -r -d '' file; do
    filename="$(basename "$file")"
    aws s3 cp "$file" "s3://$DOMAIN/$ASSET_PREFIX/$filename"
  done

echo "Deployment complete: https://$DOMAIN/"
