#!/bin/sh

# 
#  This Script emulates the groupdel command that is 
#  standard in many UNIX like Operating Systems
#  this script should be placed in /usr/sbin
#  it should be owned by root.admin and chmod 744  
#  
#  
###########

# script version
version="1.0"

#find the shell utils wee need
niutil=`which niutil`
if [ ! -x "$niutil" ];then
 >&2 echo groupdel: unable to find/use niutil	
exit 7
fi
nidump=`which nidump`
if [ ! -x "$nidump" ];then
 >&2 echo groupdel: unable to find/use nidump	
exit 7
fi
cut=`which cut`
if [ ! -x "$cut" ];then
 >&2 echo groupdel: unable to find/use cut	
exit 7
fi
grep=`which grep`
if [ ! -x "$grep" ];then
 >&2 echo groupdel: unable to find/use grep	
exit 7
fi
expr=`which expr`
if [ ! -x "$expr" ];then
 >&2 echo groupdel: unable to find/use expr	
exit 7
fi


#gets a free gid greater than 100

#are we root
check_uid() {
    if [ "`whoami`" = root ]
    then
	uID=0
    else
	if [ "$uID" = "" ]
	then
	    uID=-1
	fi
    fi
    export uID
}


usage()
{
        >&2 echo "groupdel group"
        >&2 echo "READ groupdel (8) manpage for more data."
exit $1
}

group=""
#case the options and prams
while [ $# -ne 0 ]
do
    case "$1" in
        --help)
            usage 0
            ;;
        --version)
           >&2 echo "groupdel: version $version, by Chris Roberts "
           >&2 echo "groupdel: (c) 2002 Chris Roberts <chris@osxgnu.org> "
            exit 0
            ;;
          -*)
            >&2 echo "groupdel: ERROR Unknown option: $1"
            usage 1
            ;;
        *)
 	    group="$1"
            ;;
    esac
    shift
done 


if [ -z "$group" ]
then
    >&2 echo "groupdel: ERROR MISSING VALUE: requires a group"
    usage 1
fi

check_uid
if [ $uID != 0 ]
then
	>&2 echo groupdel: you must be root
	exit 7
fi




#kill the group
if [ `$nidump group . |/usr/bin/grep -c "$group"` -eq 1 ];then
	GroupID=`$nidump group . |/usr/bin/grep "$group"|$cut -d":" -f3`
	if [ `/usr/bin/nidump passwd . |/usr/bin/cut -d":" -f4 |/usr/bin/grep -c "$GroupID"` -eq 1 ]; then
		>&2 echo "groupdel: The Group '$group' GID '$GroupID' is a primary group of user(s)"
		exit 1
	else
		$niutil -destroy . /groups/$group
	fi
else
	>&2 echo "groupdel: group '$group' not found "
	exit 7
fi

