#!/bin/sh
set -e

case "$1" in
  configure)
    # Remove any certmap we previously added to sssd.conf
    if [ -f /etc/sssd/sssd.conf ]; then
      sed -i '/### certmap tmzf5455 yourdev-session-pki/d' /etc/sssd/sssd.conf 2>/dev/null || true
      sed -i '/^\[certmap\/ad\.francetelecom\.fr\/tmzf5455\]/,/^$/d' /etc/sssd/sssd.conf 2>/dev/null || true
      sed -i '/^\[certmap\/ad\.francetelecom\.fr\]/,/^$/d' /etc/sssd/sssd.conf 2>/dev/null || true
    fi

    # Disable our old pam-auth-update profile (try_cert_auth approach)
    if command -v pam-auth-update >/dev/null 2>&1; then
      pam-auth-update --package --remove yourdev-smartcard 2>/dev/null || true
    fi

    # Register our new GDM smartcard PAM service as the GDM alternative
    if [ -f /etc/pam.d/gdm-smartcard-pkinit ]; then
      update-alternatives --install /etc/pam.d/gdm-smartcard gdm-smartcard \
        /etc/pam.d/gdm-smartcard-pkinit 60 2>/dev/null || true
      update-alternatives --set gdm-smartcard /etc/pam.d/gdm-smartcard-pkinit 2>/dev/null || true
    fi

    # Ensure SSSD CA bundle permissions
    if [ -f /etc/sssd/pki/sssd_auth_ca_db.pem ]; then
      chown root:sssd /etc/sssd/pki/sssd_auth_ca_db.pem 2>/dev/null || true
    fi

    # Ensure conf.d permissions
    for f in /etc/sssd/conf.d/*.conf; do
      [ -f "$f" ] && chown root:sssd "$f" 2>/dev/null && chmod 0640 "$f" 2>/dev/null || true
    done

    if [ -f /etc/sssd/sssd.conf ]; then
      chown root:sssd /etc/sssd/sssd.conf 2>/dev/null || true
      chmod 0600 /etc/sssd/sssd.conf 2>/dev/null || true
    fi

    # Compile dconf database for GDM smartcard setting
    if command -v dconf >/dev/null 2>&1; then
      dconf update 2>/dev/null || true
    fi

    # Restart SSSD
    if command -v systemctl >/dev/null 2>&1; then
      systemctl restart sssd 2>/dev/null || true
    fi
    ;;

  abort-upgrade|abort-remove|abort-deconfigure)
    ;;

  *)
    echo "postinst called with unknown argument '$1'" >&2
    exit 1
    ;;
esac

exit 0
