#!/usr/bin/env bash
# Workflow: PC → git push | Server (SSH) → ./scripts/deploy.sh
# Holt main von GitHub und deployt lokal per Magallanes (127.0.0.1 / ftpuser).
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"

ENV_NAME="production"
DO_PULL=1
for arg in "$@"; do
  case "$arg" in
    --no-pull) DO_PULL=0 ;;
    production|staging) ENV_NAME="$arg" ;;
  esac
done

MAGE_BIN="${MAGE_BIN:-}"
if [[ -z "$MAGE_BIN" ]]; then
  if [[ -x /usr/local/bin/mage ]]; then
    MAGE_BIN=/usr/local/bin/mage
  elif [[ -x /opt/magallanes/vendor/bin/mage ]]; then
    MAGE_BIN=/opt/magallanes/vendor/bin/mage
  else
    echo "Magallanes nicht gefunden (/usr/local/bin/mage)."
    exit 1
  fi
fi

if [[ "$DO_PULL" -eq 1 ]]; then
  echo "==> git pull --ff-only origin main"
  git fetch origin main
  git pull --ff-only origin main
else
  echo "==> git pull übersprungen (--no-pull)"
fi

echo "==> Magallanes deploy: ${ENV_NAME}"
if [[ "$(id -u)" -eq 0 ]]; then
  sudo -u ftpuser -H bash -lc "cd '$ROOT' && php '$MAGE_BIN' deploy '$ENV_NAME'"
elif [[ "$(id -un)" == "ftpuser" ]]; then
  php "$MAGE_BIN" deploy "${ENV_NAME}"
else
  echo "Bitte als root oder ftpuser ausführen (Magallanes braucht SSH als ftpuser@127.0.0.1)."
  exit 1
fi

echo "==> Deploy fertig. Live: $ROOT/current"
