#!/bin/sh

set -eu

allow() {
  exit 0
}

deny() {
  echo 'Access denied because user(s) do not allow admins in.' >&2
  exit 1
}

is_admin_user() {
  # Check if user belongs to "puavo-os"-group, which is for administrators.
  id -Gn "$PAM_USER" 2>/dev/null | tr ' ' "\n" | grep -qx puavo-os
}

# Allow "root" and "Debian-gdm" always.
if [ "$PAM_USER" = 'root' -o "$PAM_USER" = 'Debian-gdm' ]; then
  allow
fi

if ! is_admin_user; then
  deny
fi

if [ -e /run/puavo/nbd-server ]; then
  # No access restrictions on hosts which have booted from network
  # (laptops are in maintenance mode, and fatclients are... well,
  # user data is on servers anyway, and we do not know what
  # "personally administered" means on netbooting hosts).
  allow
fi

if ! puavo-conf puavo.support.show_accesscontrols_for | grep -qw ssh; then
  # If a user can not specifically allow/deny ssh in, user has no control
  # over whether admin should be allowed in, and thus we allow admin in.
  allow
fi

# check if incoming is accepted
incoming_accepted=$(
  /usr/lib/puavo-ltsp-client/admin-remote-connections --is-incoming-accepted)

if [ "$incoming_accepted" != 'yes' ]; then
  deny
fi

# okay, we let you in
allow
