#! /bin/sh
#----------------------------------------------------------------------------
# remove-group - remove a group
#
# Copyright (c) 2001-2004 Frank Meyer <frank@eisfair.org>
#
# usage: remove-group [-f] [group]
#
# Creation:	04.11.2001  fm
# Last Update:  $Id$
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#----------------------------------------------------------------------------

# include eislib
. /var/install/include/eislib


if [ "$1" = "-f" ]
then
    force=true
    shift
else
    force=false
fi

case $#
in
    0)
        interactive='true'
        group=""
        ;;
    1)
        interactive='false'
        group="$1"
        ;;
    *)
        mecho "usage: $0 [group]" >&2
        exit 1
        ;;
esac

if [ "$interactive" = "true" ]
then
    clrhome
    mecho -info "Remove group"
    mecho

    tty=`tty`

    mecho -n "Group to remove (e.g. 'www'): \c"
    read group

    if [ "$group" = "" ]
    then
        mecho
        anykey
        exit 0
    fi
fi

line=`grep "^$group:" /etc/group`

if [ "$line" = "" ]
then
    if [ "$interactive" = "true" ]
    then
        mecho
        mecho -error "Group $group does not exist"
        mecho
        anykey
    else
        mecho "Group $group does not exist" >&2
    fi
    exit 1
fi

IFS=':'
set -- $line

gid=$3

if [ $force = false ]
then
    if [ $gid -lt 200 -o $gid -ge 65534 ]
    then
        if [ "$interactive" = "true" ]
        then
            mecho
            mecho -error "It is not allowed to remove group $group, sorry"
            mecho
            anykey
        else
            mecho "It is not allowed to remove group $group, sorry" >&2
        fi
        exit 1
    fi
fi

while read line
do
    set -- $line
    g="$4"

    if [ $g = $gid ]
    then
        if [ "$interactive" = "true" ]
        then
            mecho
            mecho -error "Cannot remove group $group, user $1 is member of $group"
            mecho
            anykey <$tty
        else
            mecho "Cannot remove group $group, user $1 is member of $group" >&2
        fi
        exit 0
    fi
done </etc/passwd

grep -v "^$group:" /etc/group >/tmp/group-$$
cp /tmp/group-$$ /etc/group		# cp: keep inode & permissions
rm -f /tmp/group-$$

if [ "$interactive" = "true" ]
then
    mecho
    anykey
fi
exit 0