#!/usr/bin/env bash

set -euo pipefail

# Safe production deploy for Drupal:
# - Syncs code to origin/main deterministically
# - Runs composer install, drush updb, drush cr
# - Never runs drush cim automatically
# - Warns if config drift exists (so user/admin config is not overwritten)

REMOTE="${REMOTE:-origin}"
BRANCH="${BRANCH:-main}"
DO_CLEAN=0

# On cPanel servers, /usr/bin/php is often PHP 8.1 while the site runs PHP 8.3.
# Detect the correct PHP binary automatically (prefer 8.3, then 8.2).
PHP_BIN="${PHP_BIN:-}"
if [[ -z "$PHP_BIN" ]]; then
  for candidate in \
    /opt/cpanel/ea-php83/root/usr/bin/php \
    /opt/cpanel/ea-php82/root/usr/bin/php \
    /usr/local/bin/php83 \
    /usr/bin/php83; do
    if [[ -x "$candidate" ]]; then
      PHP_BIN="$candidate"
      break
    fi
  done
  PHP_BIN="${PHP_BIN:-php}"
fi
COMPOSER_BIN="${COMPOSER_BIN:-/opt/cpanel/composer/bin/composer}"
[[ -x "$COMPOSER_BIN" ]] || COMPOSER_BIN="$(command -v composer)"
DRUSH_BIN="${DRUSH_BIN:-vendor/bin/drush}"

for arg in "$@"; do
  case "$arg" in
    --clean)
      DO_CLEAN=1
      ;;
    *)
      echo "Unknown argument: $arg"
      echo "Usage: $0 [--clean]"
      exit 1
      ;;
  esac
done

echo "==> Pre-check"
command -v git >/dev/null || { echo "git not found"; exit 1; }
[[ -x "$COMPOSER_BIN" ]] || { echo "composer not found at $COMPOSER_BIN"; exit 1; }
PHP_VERSION=$("$PHP_BIN" -r 'echo PHP_VERSION;' 2>/dev/null)
echo "    PHP:      $PHP_BIN ($PHP_VERSION)"
echo "    Composer: $COMPOSER_BIN"
echo "    Drush:    $DRUSH_BIN"

if [[ -n "$(git status --porcelain)" ]]; then
  echo "Working tree is not clean. Commit/stash/discard local changes first."
  git status --short
  exit 1
fi

echo "==> Sync code to ${REMOTE}/${BRANCH}"
git fetch "$REMOTE"
git checkout "$BRANCH"
git reset --hard "${REMOTE}/${BRANCH}"

if [[ "$DO_CLEAN" -eq 1 ]]; then
  echo "==> Cleaning untracked files (git clean -fd)"
  git clean -fd
else
  echo "==> Skipping git clean (use --clean to enable)"
fi

echo "==> Install dependencies"
"$PHP_BIN" "$COMPOSER_BIN" install --no-dev -o --no-interaction

echo "==> Run Drupal updates"
"$DRUSH_BIN" updb -y
"$DRUSH_BIN" cr

echo "==> Check config drift (no import)"
if "$DRUSH_BIN" cst 2>/dev/null | grep -qE "No differences|there are no changes"; then
  echo "Config status: clean"
else
  echo "Config status: differences detected"
  echo "Review before any config import:"
  echo "  $DRUSH_BIN cst"
  echo "  # optional: $DRUSH_BIN cex -y (to preserve prod changes into sync dir)"
fi

echo "==> Done"
