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

# Farben
GREEN="\033[0;32m"
RED="\033[0;31m"
NC="\033[0m"

log() { echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')] $*${NC}"; }
err() { echo -e "${RED}[$(date +'%Y-%m-%d %H:%M:%S')] $*${NC}" 1>&2; }

ensure_command() {
  local cmd="$1"
  command -v "$cmd" >/dev/null 2>&1
}

bootstrap_node() {
  # In non-interactive SSH sessions, node/npm might not be on PATH (e.g. nvm in .bashrc).
  if ensure_command npm && ensure_command node; then
    return 0
  fi
  if [ -s "$HOME/.nvm/nvm.sh" ]; then
    # shellcheck disable=SC1090
    . "$HOME/.nvm/nvm.sh"
    # Prefer default alias if configured, otherwise keep current.
    nvm use --silent default >/dev/null 2>&1 || true
  fi
}

bootstrap_node
if ! ensure_command git; then err "git not found in PATH"; exit 127; fi
if ! ensure_command npm; then err "npm not found in PATH"; exit 127; fi

log "Fetching latest changes..."
git fetch --all --prune || { err "git fetch failed"; exit 1; }

log "Pulling latest changes..."
git pull --ff-only || { err "git pull failed"; exit 1; }

log "Installing dependencies..."
npm ci || npm install || { err "npm install failed"; exit 1; }

log "Building frontend..."
npm run build || { err "build failed"; exit 1; }

log "Copying dist -> public..."
mkdir -p public || true
cp -R dist/* public/ || { err "copy dist failed"; exit 1; }

log "Restarting service miriamgemeinde..."
if [ "${EUID:-$(id -u)}" -eq 0 ]; then
  systemctl restart miriamgemeinde || { err "service restart failed"; exit 1; }
else
  # Non-interactive deploys (CI) must not prompt for a sudo password.
  # Configure on the server (recommended):
  #   sudo visudo -f /etc/sudoers.d/miriamgemeinde
  #   torsten ALL=NOPASSWD:/bin/systemctl restart miriamgemeinde,/bin/systemctl status miriamgemeinde
  sudo -n systemctl restart miriamgemeinde || {
    err "service restart failed (no password prompt). Configure passwordless sudo for 'systemctl restart miriamgemeinde' or run deploy as root."
    exit 1
  }
fi

log "Deployment completed successfully."
