#!/bin/bash
set -euo pipefail

APP_ROOT="${1:-/home/smaraxam/hyreall.com/me}"
SRC_ROOT="$(cd "$(dirname "$0")" && pwd)"
mkdir -p "$APP_ROOT"

normalize_path() {
  python3 - <<'PY' "$1"
import os, sys
print(os.path.realpath(sys.argv[1]))
PY
}

SRC_REAL="$(normalize_path "$SRC_ROOT")"
APP_REAL="$(normalize_path "$APP_ROOT")"

if [ "$SRC_REAL" = "$APP_REAL" ]; then
  echo "This deploy.sh is being run from the live app folder itself." >&2
  echo "Run the deploy script from the extracted package folder instead:" >&2
  echo "  cd /home/smaraxam/hyreall.com/hyreme-namecheap-package" >&2
  echo "  bash deploy.sh /home/smaraxam/hyreall.com/me" >&2
  exit 1
fi

cleanup_path() {
  local target="$1"
  if [ -e "$APP_ROOT/$target" ]; then
    rm -rf "$APP_ROOT/$target"
  fi
}

kill_app_processes() {
  local app_root="$1"
  local current_pid="$$"
  local pids=""

  if command -v pgrep >/dev/null 2>&1; then
    pids="$(pgrep -u "$(id -u)" -f "$app_root" || true)"
  else
    pids="$(ps -u "$(id -u)" -o pid= -o command= | awk -v app="$app_root" 'index($0, app) > 0 {print $1}' || true)"
  fi

  if [ -z "$pids" ]; then
    echo "No existing app processes matched $app_root"
    return 0
  fi

  echo "Stopping existing app processes for $app_root"
  for pid in $pids; do
    if [ "$pid" = "$current_pid" ]; then
      continue
    fi
    kill "$pid" 2>/dev/null || true
  done

  sleep 2

  local survivors=""
  for pid in $pids; do
    if [ "$pid" = "$current_pid" ]; then
      continue
    fi
    if kill -0 "$pid" 2>/dev/null; then
      survivors="$survivors $pid"
    fi
  done

  if [ -n "$survivors" ]; then
    echo "Force killing stubborn app processes:$survivors"
    for pid in $survivors; do
      kill -9 "$pid" 2>/dev/null || true
    done
  fi
}

kill_app_processes "$APP_ROOT"

# Remove previous runtime and common source/deploy clutter while preserving .env
# and any CloudLinux-managed node_modules symlink.
cleanup_path ".next"
cleanup_path "public"
cleanup_path "app"
cleanup_path "components"
cleanup_path "lib"
cleanup_path "prisma"
cleanup_path "scripts"
cleanup_path "styles"
cleanup_path ".deploy-backups"
cleanup_path "DEPLOY.txt"
cleanup_path "cleanup-old-deploys.sh"
cleanup_path "deploy.sh"
cleanup_path "runtime"
cleanup_path "tmp"
cleanup_path "next.config.js"
cleanup_path "tsconfig.json"
cleanup_path "postcss.config.js"
cleanup_path "tailwind.config.ts"
cleanup_path "middleware.ts"
cleanup_path "server.js"
cleanup_path "server.next.js"
cleanup_path "ensure-default-user.js"
cleanup_path "package.json"
cleanup_path "package-lock.json"
cleanup_path "pnpm-lock.yaml"
cleanup_path "yarn.lock"
cleanup_path ".npmrc"
cleanup_path ".yarnrc"
cleanup_path ".yarnrc.yml"
cleanup_path "README.md"
cleanup_path "node_modules_packaged_backup"
cleanup_path "node_modules_backup"
cleanup_path ".pnpm-store"
cleanup_path ".npm"
cleanup_path ".cache"
cleanup_path ".local-dev-db.json"

if [ -d "$APP_ROOT/node_modules" ] && [ ! -L "$APP_ROOT/node_modules" ]; then
  rm -rf "$APP_ROOT/node_modules"
fi

cp -R "$SRC_ROOT"/. "$APP_ROOT"/
chmod +x "$APP_ROOT/server.js" "$APP_ROOT/deploy.sh" "$APP_ROOT/cleanup-old-deploys.sh" || true

if command -v node >/dev/null 2>&1; then
  node "$APP_ROOT/ensure-default-user.js" || true
fi

# Delete any backup remnants or uploaded archives/folders after the new runtime is in place.
rm -rf "$APP_ROOT/.deploy-backups" \
       "$HOME/hyreme-app-upload" \
       "$HOME/hyreme-app-local-deploy" \
       "$HOME/hyreme-app-standalone-deploy" \
       "$HOME/hyreme-app-deploy" \
       "$HOME/hyreme-app-local-runtime" \
       "$HOME/hyreme-app-build"
rm -f "$HOME/hyreme-app-local-deploy.zip" \
      "$HOME/hyreme-app-deploy.zip" \
      "$HOME/hyreme-app-standalone-deploy.zip" \
      "$HOME/hyreme-app.zip" \
      "$HOME/app.zip"

echo
echo "Optimized standalone runtime deployed to: $APP_ROOT"
mkdir -p "$APP_ROOT/tmp"
touch "$APP_ROOT/tmp/restart.txt"
echo "Passenger restart requested via tmp/restart.txt"
echo "Startup file should be: server.js"
echo "App-specific processes were cleaned before deployment."
