#!/bin/sh -e

##########################################################################
#   Script description:
#       Sync groups from head node
#       
#       FIXME: Factor out OS dependencies to auto-admin
#
#   History:
#   Date        Name        Modification
#   2016-08-15  root        Begin
##########################################################################

usage()
{
    printf "Usage: $0 node groupname [groupname ...]\n"
    exit 1
}


##########################################################################
#   Main
##########################################################################

if [ $# -lt 2 ]; then
    usage
fi

node="$1"
shift
groups=$(echo $@ | sed -e 's|,| |g')

for group_name in $groups; do
    printf "Adding group $group_name...\n"
    group_id=`awk -F : -v group_name=$group_name '$1 == group_name { print $3 }' \
	/etc/group`
    
    case `ssh $node auto-ostype` in
    RHEL)
	# -f = return success even if the group already exists
	ssh $node groupadd -f -g $group_id $group_name
	;;
    
    FreeBSD)
	if ! ssh $node pw groupadd $group_name -g $group_id; then
	    printf 'Group add failed.\n'
	fi
	;;
    
    *)
	printf "$0: Not supported on $(auto-ostype).\n"
	exit 1
	;;

    esac
done
