#!/bin/sh
set -e

# GDM greeter status panel — shows Capnis enrollment state for the selected user.
# Wire from a custom greeter before password entry, or run manually on the login screen.

USER="${1:-${GDM_USER:-${PAM_USER:-}}}"
if [ -z "$USER" ] || [ "$USER" = "gdm" ] || [ "$USER" = "root" ]; then
  echo "Usage: $0 <linux-username>" >&2
  exit 1
fi

if ! command -v capnis-enroll >/dev/null 2>&1; then
  exit 0
fi

STATUS="$(capnis-enroll greeter-status "$USER" 2>/dev/null || true)"
if [ -z "$STATUS" ]; then
  exit 0
fi

if printf '%s' "$STATUS" | grep -q '"enrolled"[[:space:]]*:[[:space:]]*true'; then
  NAME="$(printf '%s' "$STATUS" | sed -n 's/.*"employee_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')"
  EMAIL="$(printf '%s' "$STATUS" | sed -n 's/.*"employee_email"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')"
  LABEL="${NAME:-Capnis employee}"
  if [ -n "$EMAIL" ]; then
    TEXT="This account is enrolled for Capnis SSO.\n\n${LABEL}\n${EMAIL}\n\nSelect the user and sign in (no password required)."
  else
    TEXT="This account is enrolled for Capnis SSO.\n\nSelect the user and sign in (no password required)."
  fi

  if [ -n "${DISPLAY:-}" ] && command -v zenity >/dev/null 2>&1; then
    zenity --info --title="Capnis sign-in" --text="$TEXT" --width=360 || true
  else
    printf '%s\n' "$STATUS"
  fi

  exit 0
fi

if [ -n "${DISPLAY:-}" ] && command -v zenity >/dev/null 2>&1; then
  if zenity --question \
    --title="Capnis sign-in" \
    --text="This account is not enrolled for Capnis SSO.\n\nEnroll now with a code on your phone?" \
    --ok-label="Enroll" \
    --cancel-label="Use password"; then
    exec capnis-greeter-hook "$USER"
  fi
else
  printf '%s\n' "$STATUS"
fi
