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

REPO_DIR="/var/www/vhosts/karma-subito-and-marketing-admin-panel/httpsdocs"
BRANCH="dev"

cd "$REPO_DIR"

echo "== Fetch latest =="
git fetch --all

# We deploy from origin/main
git reset --hard origin/dev

# If your workspace is healthy, keep this (fast + consistent):
# pnpm install --frozen-lockfile
#
# If your workspace sometimes breaks due to other packages,
# you can still do root install once and then filter builds.
pnpm install --no-frozen-lockfile

deploy_app () {
  local app="$1"
  echo "== Build: $app =="
  pnpm --filter "$app" build

  echo "== Restart PM2: $app =="
  pm2 restart "$app" --update-env

  echo "== Done: $app =="
}

# If no args, exit (safety)
if [ "$#" -eq 0 ]; then
  echo "No apps passed. Nothing to deploy."
  exit 0
fi

for app in "$@"; do
  case "$app" in
    core|admin-console|marketing-cms|marketing-landing-page|karma-chatbot-frontend-nextJS)
      deploy_app "$app"
      ;;
    *)
      echo "Skipping unknown app: $app"
      ;;
  esac
done

pm2 save
pm2 status

