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

# WebSSH wrapper – runs as root via sudo, then switches to customer user.
#
# Usage: whfpanel_webssh_shell <loginname>

LOGINNAME="${1:-}"

if [[ -z "${LOGINNAME}" ]]; then
  echo "Usage: whfpanel_webssh_shell <loginname>" >&2
  exit 2
fi

if ! [[ "${LOGINNAME}" =~ ^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$ ]]; then
  echo "Invalid loginname" >&2
  exit 1
fi

# Panel root:
# Der Wrapper liegt typischerweise unter /usr/local/bin, daher kann man das Repo-Root
# nicht relativ zum Script-Pfad ableiten. Wir verwenden feste Kandidaten und optional
# WHFPANEL_ROOT (falls du das später sauber konfigurieren willst).
PANEL_ROOT="${WHFPANEL_ROOT:-}"

if [[ -z "${PANEL_ROOT}" ]]; then
  for cand in \
    "/var/www/system/htdocs/whfpanel" \
    "/var/www/system/home/whfpanel" \
    "/var/www/whfpanel" \
    "/opt/whfpanel"
  do
    if [[ -f "${cand}/services/webssh/validate_user.php" ]]; then
      PANEL_ROOT="${cand}"
      break
    fi
  done
fi

VALIDATOR="${PANEL_ROOT}/services/webssh/validate_user.php"

if [[ ! -f "${VALIDATOR}" ]]; then
  echo "Validator not found: ${VALIDATOR}" >&2
  exit 1
fi

# Panel läuft bei dir mit PHP 7.4; CLI-Validator soll dieselbe Runtime nutzen.
PHP_BIN="${WHFPANEL_PHP_BIN:-}"
if [[ -z "${PHP_BIN}" ]]; then
  if command -v php7.4 >/dev/null 2>&1; then
    PHP_BIN="php7.4"
  else
    PHP_BIN="php"
  fi
fi

if ! "${PHP_BIN}" "${VALIDATOR}" "${LOGINNAME}"; then
  echo "User not allowed or not active" >&2
  exit 1
fi

# Extra sanity: user must exist in NSS
if ! id "${LOGINNAME}" >/dev/null 2>&1; then
  echo "User does not exist: ${LOGINNAME}" >&2
  exit 1
fi

# Switch to customer user (login shell)
if command -v runuser >/dev/null 2>&1; then
  exec runuser -l "${LOGINNAME}"
fi

# Fallback
exec su - "${LOGINNAME}"

