#!/bin/sh

# This file is a part of ALT Linux SeLinux policy.
# Copyright (C) 2013 ALT Linux company

readonly PROG="${PROG:-${0##*/}}"
readonly PAM_TYPE_REQ="open_session"

# Helper runs in trusted domain.
MKDIRS="/etc/security/alt.newrole/mkdirs"

msg() {
    logger -t "$PROG" "$@"
    echo "$PROG --" "$@" >&2
}

fatal () {
    msg "FATAL:" "$@"
    exit 1
}

verbose() {
    if [ -n "$VERBOSE" ]; then
        msg "VERBOSE:" "$@"
    fi
}

if [ "$PAM_TYPE" != "$PAM_TYPE_REQ" ]; then
    msg "Possible only call from PAM '$PAM_TYPE_REQ' stage."
    exit 0
fi

if [ "${#*}" -ne 1 ]; then
    fatal "Use: $PROG <CONFIG>"
fi

if ! [ -r "$1" ]; then
    fatal "Can't read config file: $1"
fi

if ! [ -x "$MKDIRS" ]; then
    fatal "Can't find helper: $MKDIRS"
fi

# Include configuration file
. "$1"

verbose "ARGS: $@"
verbose "ID: $(id)"
verbose "ENV: $(env)"
verbose "PAM_USER: $PAM_USER"
verbose "PAM_TYPE: $PAM_TYPE"

if [ -z "$PAM_USER" ]; then
    fatal "Can't get PAM_USER from env"
fi

for u in $SKIP_USERS; do
    if [ $u = $PAM_USER ]; then
        msg "User '$PAM_USER' listed in SKIP_USERS. Exit."
        exit 0
    fi
done
verbose "User '$PAM_USER' is not listed in SKIP_USERS='$SKIP_USERS'. Continue."

if [ -n "$ONLY_USERS" ]; then
  cont=
  for u in $ONLY_USERS; do
    if [ $u = $PAM_USER ]; then
      msg "User '$PAM_USER' listed in ONLY_USERS. Continue."
      cont="yes"
    fi
  done
  if [ -z "$cont" ]; then
    verbose "User '$PAM_USER' is not listed in ONLY_USERS='$ONLY_USERS'. Exit."
    exit 0
  fi
fi

readonly USER_GROUPS_IDS="$(getent initgroups "$PAM_USER" | sed -n -e "s/^$PAM_USER[[:space:]]\+//p")"
readonly USER_GROUPS="$(getent group $USER_GROUPS_IDS | sed -n -e 's/:.\+$//p' | tr '\n' ' ')"
verbose "User '$PAM_USER' belong to '$USER_GROUPS' groups"

for g in $SKIP_GROUPS; do
    for gu in $USER_GROUPS; do
        if [ $g = $gu ]; then
            msg "User belong to group '$g' which is listed in SKIP_GROUPS. Exit."
            exit 0
        fi
    done
done
verbose "User '$PAM_USER' doesn't belong to any SKIP_GROUPS='$SKIP_GROUPS'. Continue."

if [ -n "$ONLY_GROUPS" ]; then
  cont=
  for g in $ONLY_GROUPS; do
    for gu in $USER_GROUPS; do
      if [ $g = $gu ]; then
        msg "User belong to group '$g' which is listed in ONLY_GROUPS. Continue."
        cont="yes"
      fi
    done
  done
  if [ -z "$cont" ]; then
    verbose "User '$PAM_USER' doesn't belong to any ONLY_GROUPS='$ONLY_GROUPS'. Exit."
    exit 0
  fi
fi

# Create directories
"$MKDIRS" || fatal "Can't create user's dirs"

# vim: ai ts=2 sw=2 et sts=2 ft=sh
# vim: autoindent tabstop=2 shiftwidth=2 expandtab softtabstop=2 filetype=sh
