#!/bin/bash
#
# Convert unix group file to LDIF
#
# Maximilian Wilhelm <debian-edu@rfc3514>
#  -- Mon, 16 Aug 2004 17:55:40 +0200
#


#
# Variables
#

# User maintaned Variables
GROUPBASE="ou=group,dc=skole,dc=skolelinux,dc=no"


# Script maintaned
GROUPFILE=""
LDIFOUT=""
EMPTYGROUPS=""
TMPFILE="/tmp/group2ldif.$$.tmp"


#
# Some fency functions
#

#
# How I want to be used.
usage()
{
	echo "Usage: $0 -g <groupfile> [ -lo <ldif output> ] [ --include-empty-groups ] [ -h | -help ]"
	exit 1
}

#
# Simple group file validation
checkgroup()
{
	if [ ! -s $GROUPFILE -a ! -r $GROUPFILE ]; then
		echo "File \"${GROUPFILE}\" does not exist or is not readable" >&2
		exit 1
	elif [ `grep -c '[a-z]\+:[[:space:]x*]:[0-9]\+:.*' ${GROUPFILE}` -lt 1 ]; then
		echo "File \"${GROUPFILE}\² seems not to be a valid group file." >&2
		exit 1
	fi
}

ldifgen()
{
while read line;
do
	group=`echo ${line} | cut -d: -f1`
	gid=`echo ${line} | cut -d: -f3`
	users=`echo ${line} | cut -d: -f4`

	if [ "${EMPTYGROUPS}" == "yes" -o "${users}" ]; then
	 # Group not empty, convert it.

		# Group header
		cat << EOF >> ${TMPFILE}

dn: cn=${group},${GROUPBASE}
objectClass: posixGroup
objectClass: top
cn: ${group}
gidNumber: ${gid}
EOF

		# users
		echo ${users} | tr ',' '\n' | while read user;
		do
			echo "memberUid: ${user}" >> ${TMPFILE}
		done
	else
	 # Group is empty, don't convert
		echo "Group ${group} is empty, not converted" >&2

	fi

done < ${GROUPFILE}


}

#
# What to do with the output?
output()
{
	if [ "${LDIFOUT}" ]; then
		cp ${TMPFILE} ${LDIFOUT};
	else
		cat ${TMPFILE}
	fi
}



#
# Let the show begin
#


# What to do?
[ $# == 0 ] && usage >&2

while [ $# -gt 0 ]; do
    case "$1" in
        -g)			GROUPFILE="$2" ;;
        -lo)			LDIFOUT="$2" ;;
        --include-empty-groups)	EMPTYGROUPS="yes" ;;
        -help|-h)		usage ;;
    esac
    shift
done

[ -z ${GROUPFILE} ] && usage>&2

# Valid file?
checkgroup

# OK, let's convert it
ldifgen

# Tell the world
output

# remove tmpfile
rm ${TMPFILE}
