#!/bin/sh
# $1 direccion de correo, $2 clave
#
DIRECTORIO=/home
#ADMINDN="cn=admin,dc=unanleon,dc=edu,dc=ni"
DEBUG=""
#MAILUSER=

BASEDN=`cat /etc/ldap/ldap.conf |\
    while read TOKEN PARAM BASURA; do
     if [ "$TOKEN" == "BASE" ]; then echo $PARAM; exit ; fi
    done`
LDAPHOST=`cat /etc/ldap/ldap.conf |\
    while read TOKEN PARAM BASURA; do
     if [ "$TOKEN" == "HOST" ]; then echo $PARAM; exit ; fi
    done`

MBOX=$1
PASS=$2

if [ -z "$MBOX" ]; then
    read -p "Introducir cuenta (con dominio): " MBOX
fi

if [ -z "$PASS" ]; then
    read -p "Introducir contraseña: " PASS
fi

if [ -z "$BASEDN" ]; then
    read -p "Introducir BaseDN: " BASEDN
fi

if [ -z "$ADMINDN" ]; then
    ADMINDN="cn=admin,"$BASEDN
fi


CUENTA=`echo $MBOX|cut -d@ -f1`

if [ -z "$CUENTA" ]; then echo "nombre de cuenta vacia"; exit -1; fi

DOMINIO=`echo $MBOX|cut -d@ -f2`

if [ -z "$DOMINIO" -o "$CUENTA" == "$DOMINIO" ]; then
    echo "domino de cuenta vacia"; exit -1;
fi

if [ -z "$DIRECTORIO" ]; then
    DIRECTORIO=/var/mail/store/`echo $DOMINIO|cut -d. -f1`
    if [ "/var/mail/store/" == "$DIRECTORIO" ]; then echo "dominio inválido: $DOMINIO"; exit -1; fi
fi

if [ -z "$MAILUSER" ]; then
    MAILUSER=mailuser
fi

MAILUSERUID=`getent passwd $MAILUSER |  cut -d: -f3`
MAILUSERGID=`getent passwd $MAILUSER |  cut -d: -f4`


CRYPT=$(/usr/sbin/slappasswd -c '$1$%.8s' -h {crypt} -s $PASS)


$DEBUG ldapadd -x -D "$ADMINDN" -W \
    -h $LDAPHOST <<EOF
dn: uid=$CUENTA,ou=People,$BASEDN
objectClass: account
objectClass: posixAccount
objectClass: top
objectClass: shadowAccount
objectClass: qmailUser
cn: $CUENTA
uid: $CUENTA
uidNumber: $MAILUSERUID
gidNumber: $MAILUSERGID
loginShell: /bin/false
mail: $CUENTA@$DOMINIO
homeDirectory: $DIRECTORIO/$CUENTA
userPassword: ${CRYPT/CRYPT/crypt}
EOF
