#!/bin/sh
set -e

# GDM greeter hook: print enrollment JSON and optionally launch device enrollment.
# Wire from a custom greeter or run manually at the login screen.

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

STATUS="$(capnis-enroll greeter-status "$USER" 2>/dev/null || true)"
if [ -n "$STATUS" ]; then
  printf '%s\n' "$STATUS"
fi

if printf '%s' "$STATUS" | grep -q '"enrolled"[[:space:]]*:[[:space:]]*true'; then
  exit 0
fi

if [ -n "${DISPLAY:-}" ] && command -v zenity >/dev/null 2>&1; then
  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" || exit 0
fi

exec capnis-gdm-enroll "$USER"
