#!/bin/sh
#
# $Log: authgeneric.in,v $
# Revision 1.1  2019-05-29 00:45:02+05:30  Cprogrammer
# Initial revision
#
# Revision 2.2  2016-06-17 10:39:25+05:30  Cprogrammer
# FHS compliance
#
# Revision 2.1  2010-11-12 19:37:28+05:30  Cprogrammer
# authmodule to create users on imap/pop3 login (written for way2sms)
#
#

# $Id: authgeneric.in,v 1.1 2019-05-29 00:45:02+05:30 Cprogrammer Exp mbhangui $
if [ $# -lt 2 ] ; then
	echo "Incorrect arguments" 1>&2
	echo "AUTHFAILURE" 1>&2
	exit 2
fi
AWK=$(which awk)
data_input=`cat 0<&3`
USER=`echo $data_input | cut -d ' ' -f3`
PASSWORD=`echo $data_input | cut -d ' ' -f4`
user=$(echo $USER | $AWK -F'@' '{print $1}')
domain=$(echo $USER | $AWK -F'@' '{print $2}')
if [ -z $domain ] ; then
	domain=$DEFAULT_DOMAIN
fi
#
# create the user here
#
/usr/bin/vadduser -d "$user"@"$domain" $PASSWORD > /dev/null
if [ $? -ne 0 ] ; then
	if [ $? -eq 17 ] ; then
		echo "authgeneric: user exists" 1>&2
		exec 4>/tmp/courier_auth.$$ 3</tmp/courier_auth.$$
		/bin/rm -f /tmp/courier_auth.$$
		# supply the original input on fd 3
		echo $data_input | tr [" "] ["\n"] 1>&4
		exec $*
	else
		echo "authgeneric: vadduser failed" 1>&2
	fi
	exit 1
fi
# set environment variables
AUTHENTICATED=$USER
AUTHADDR=$USER
AUTHFULLNAME=$user
# do vuserinfo to set MAILDIRQUOTA environment variable
/usr/bin/vuserinfo $AUTHENTICATED > /tmp/courier_auth.$$
if [ $? -eq 0 ] ; then
	quota=`cat /tmp/courier_auth.$$ |grep quota|head -1 | cut -d: -f2 | awk '{print $1}'`
	MAILDIRQUOTA=$quota"S","0C"
	HOME=`cat /tmp/courier_auth.$$ |grep dir |awk '{print $3}'`
	/bin/rm -f /tmp/courier_auth.$$
	MAILDIR=$HOME/Maildir
	export AUTHENTICATED AUTHADDR AUTHFULLNAME MAILDIRQUOTA HOME MAILDIR
	if [ ! -d $MAILDIR ] ; then
		/usr/bin/maildirmake $MAILDIR > /dev/null
		if [ $? -ne 0 ] ; then
			echo "authgeneric: maildirmaike $MAILDIR failed" 1>&2
			exit 1
		fi
	fi
	cd $HOME
	if [ $? -eq 0 ] ; then
		exec $*
	else
		echo "authgeneric: cd $HOME failed" 1>&2
		exit 1
	fi
else
	/bin/rm -f /tmp/courier_auth.$$
	echo "authgeneric: userinfo failed" 1>&2
	exit 1
fi
if [ $# -lt 3 ] ; then
	echo "authgeneric: no more modules will be tried" 1>&2
	echo "AUTHFAILURE" 1>&2
	exit 1
fi

# call the next auth module on command line
exec 4>/tmp/courier_auth.$$ 3</tmp/courier_auth.$$
/bin/rm -f /tmp/courier_auth.$$
# supply the original input on fd 3
echo $data_input | tr [" "] ["\n"] 1>&4
exec $*
