#!/bin/sh
set -e

# Run from a GDM greeter session or login screen helper.
# Example greeter hook: run as the selected user before password entry.

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

PROVISION=0
if [ "${2:-}" = "--provision-user" ] || [ "${CAPNIS_AUTO_PROVISION:-}" = "1" ]; then
  PROVISION=1
elif [ -f /etc/capnis-workstation/config.yaml ] && grep -Eq '^auto_provision_user:\s*true\s*$' /etc/capnis-workstation/config.yaml; then
  PROVISION=1
fi

if [ -n "${DISPLAY:-}" ] && command -v zenity >/dev/null 2>&1; then
  zenity --question \
    --title="Capnis workstation enrollment" \
    --text="Enroll this computer with Capnis employee SSO?\n\nYou will receive a code to approve on your phone." \
    --ok-label="Enroll" \
    --cancel-label="Use password" || exit 0
fi

su - "$USER" -c "capnis-enroll gdm-enroll"

if [ "$PROVISION" -eq 1 ] && [ "$(id -u)" -eq 0 ]; then
  capnis-enroll provision-user --username "$USER" || true
fi
