#!/bin/sh
#writen by Zane C. Bowers <vvelox@vvelox.net>

. `which sh-include`
include random
include lugtools

usage(){
    echo "lgadd: add a POSIX group to LDAP for use with NSS LDAP"
    echo "version 0.1.2"
    echo ""
    echo "-c <file> the config file to use... the default is ~/.lugtools"
    echo "-G <GID>  the GID of the group to add"
    echo "-u <camma seperated list> a list of users to be put in the group initially"
    echo ""
    echo "required:"
    echo "-g <group>	 the primary group of the user"
    echo ""
    echo "-h	display this"
}

#default config file
config=~/.lugtools

#get the options
while getopts hg:G:u:h OPTION ; do
    case "$OPTION" in
	g) groupname="$OPTARG" ;;
	G) GID="$OPTARG" ;;
	u) USERlist="$OPTARG" ;;
        h) usage=true ;;
       \?) usage=true ;;
    esac
done

#if usage is defined, print the usage info and exit
if  [ ! -z $usage ]; then
    usage;
    exit 1;
fi

#includes the config file
if [ -e $config ]; then
    . $config
else
    echo $config does not exist
    exit 1
fi

#exit if no groupname is specified
if [ -z $groupname ]; then
    echo "-g not used to define a groupname"
    exit 1
fi

#exits if the group already exists
if [ `groupExists $groupname` = "true" ]; then
    echo "$groupname already exists"
    exit 1
fi

#
if [ -z $GID ]; then
    GID=`nextGID $GIDstart`
else
    if [ `groupExists $GID` = "true" ]; then
	echo "GID $GID already in use"
	exit 1
    fi        
fi



#makes sure all the users passed to it using -u exist
if [ ! -z $USERlist ]; then
    
    #make sure it has a , in it for cut
    USERlist="$USERlist,"
    USERlist=`echo $USERlist | sed 's/,,/,/'` #clean up any double ,,
    
    USERlistCount=1
    USERlistLoop=1
    while [ $USERlistLoop = "1" ]; do
	USERlistItem=`echo $USERlist | cut -d, -f$USERlistCount`
	if [ -z $USERlistItem ]; then
	    USERlistLoop="0"
	else
	    if [ `userExists $USERlistItem` = "false" ]; then
		echo "$USERlistItem is a non-existant user"
		exit 1
	    fi
	fi
    
	USERlistCount=`expr 1 + $USERlistCount`
    done
fi


addLDAPposixGroupCheck=`addLDAPposixGroup "$groupname" "$GID" "$USERlist" "$GROUPBASE" "$USERBASE" "$BIND" "$PASSWDFILE"`
if [ $addLDAPposixGroupCheck = "true" ]; then
    echo "$groupname, $GID, has successfully been added"
else
    echo "$groupname, $GID, has failed"
    exit 1
fi


syntax highlighted by Code2HTML, v. 0.9.1