#!/bin/sh
# DocumentId:	$Id: update-twinspot-groups 1055 2001-08-08 14:04:00Z olalu $
# Author:	$Author: olalu $
# Date:		$Date: 2001-08-08 16:04:00 +0200 (ons, 08 aug 2001) $
# Summary:
#	Updates the twinspot base groups.

# Read the default twinspot config.
. /usr/share/twinspot/defaults.conf
. /usr/share/twinspot/change.func

for TEST in / /etc ; do
    if mount | grep "on[[:space:]][[:space:]]*$TEST[[:space:]].*type[[:space:]][[:space:]]*nfs[[:space:]]" > /dev/null 2>&1 ; then
	echo "Does not add or remove groups when $TEST is nfsmounted."
	exit 0
    fi
done

# Groups that exist in password file.
EGROUPS=$(grep "^[^:]*:[^:]*:[3-4][0-9][0-9]:" $GRPF | sed -e "s|:.*||g;")

# Groups that should exist.

FGROUPS=$(find $GROUPSRC -maxdepth 3 -path "$GROUPSRC/*/*/exist" -type f | sed -e "s|/CVS||;" | sed -e "s|/exist||;" | sed -e "s|.*/||;" | sort -u)

# Who should be added or changed.

for AG in $FGROUPS ; do
    . $GROUPSC
    if [ -f $GROUPSRC/$AG ] ; then
	. $GROUPSRC/$AG
    fi
    if ! echo "$EGROUPS" | grep "^$AG$" > /dev/null 2>&1 ; then
	if grep "^$AG:" $GRPF > /dev/null 2>&1 ; then
	    GPID=$(grep "^$AG:" $GRPF | sed -e "s|^[^:]*:[^:]*:\([^:]*\):.*|\1|")
	    if [ $GPID -ge 100 ] ; then
		echo "Group $AG ($GPID) does already exist, FIX THIS MANUALLY!!!"
	    fi
	else
	    SEGID=300
	    while [ -z "$FOUND" ] ; do
		if ! grep "^[^:]*:[^:]:$SEGID:" $GRPF > /dev/null 2>&1 ; then
		    groupadd -g $SEGID $AG
		    FOUND=yes
		fi
		SEGID=$(($SEGID+1))
	    done
	fi
    fi
    changefile "s|^\($AG:[^:]*:[0-9]*:\).*|\1|;" $GRPF
    find $GROUPSRC -maxdepth 3 -path "$GROUPSRC/*/$AG/members" -type f -exec cat {} \; | sort -u | {
	while read -e U ; do
	    if [ ! -z "$U" ] ; then
		adduser --quiet $U $AG
	    fi
	done
    }
done

# When removing a group do the following:
# * groupdel $GROUP

for RG in $EGROUPS ; do
    GPID=$(grep "^$RG:" $GRPF | sed -e "s|^[^:]*:[^:]*:\([^:]*\):.*|\1|")
    if [ $GPID -ge 500 ] ; then
	echo "Group $RG is a ordinary group and should not be removed."
	echo "THIS SHOULD NEVER HAPPEN, error in update script."
    elif [ $GPID -lt 300 ] ; then
	echo "Group $RG is a system group and should not be removed."
	echo "THIS SHOULD NEVER HAPPEN, error in update script."
    elif ! echo "$FGROUPS" | grep "^$RG$" > /dev/null 2>&1 ; then
	echo "Del group $RG"
	groupdel $RG
    fi
done
