#!/bin/sh

usage () {
   cat <<...
Usage: $0 [options] [group]
options: -a|--add:    Add group if it does not yet exists
         -c|--comma:  Print comma separated list
         -s|--simple: Print only user names no real names in brackets
         -h|--help:   Print this help
group: existing group from /etc/group or group to create if -a is given
...
}

# Flag whether a group should be added if missing
# Default: Do not add, just exit with error message
ADD=0
# Flag whether the list of users should be comma separated
# Default: No commas
COMMA=0
# Flag whether to print user list with real names or just usernames
# Default: username (real name)
SIMPLE=0

# Helper string for parsing input
GR=""

while [ _"$1"_ != __ ] ; do
   case "$1" in
      "-a"|"--add")
            ADD=1
            ;;
      "-c"|"--comma")
            COMMA=1
            ;;
      "-s"|"--simple")
            SIMPLE=1
            ;;
      "-h"|"--help")
            usage
            exit
            ;;
      *)
            GR="$1"
            ;;
   esac
   shift
done

case "$GR" in
   "")
            GROUP=""
	    ;;
   "-"*)
            echo "Wrong option $GR."
            usage
	    exit -1
	    ;;
   *)
	    TESTGROUP="`getent group ${GR}`" || true
            if [ -z "${TESTGROUP}" ] ; then
               echo "Group $GR does not exist on this system."
	       if [ ${ADD} -eq 0 ] ; then
                   usage
		   exit -1
	       fi
               /usr/sbin/addgroup --system "${GR}" >/dev/null
	       # if the group was just created it can not have any users ...
	       # so simply exit here with no output
    	       exit
	    fi
	    GROUP="$GR"
	    ;;
esac

TMPFILE=`tempfile`

if [ -f /etc/adduser.conf ] ; then
   source /etc/adduser.conf
fi
if [ _"$FIRST_UID" = _"" ] ; then
  FIRST_UID=1000
fi

(IFS=":"
   while read user pass uid gid name rest ; do
      if [ $uid -ge $FIRST_UID -a "$user" != "nobody" ] ; then
         name=`echo $name | sed "s/,.*//"`
         if [ $SIMPLE -eq 1 ] ; then
            echo "$user" >> ${TMPFILE}
         else
            echo "$user ($name)" >> ${TMPFILE}
         fi
      fi
   done < /etc/passwd
)

if [ _"$GROUP"_ != __ ] ; then
   USERS=`echo "${TESTGROUP}" | sed "s/.*:\([^:]*\)/\1/" | tr ',' '\n'`
   if [ _"$USERS"_ = __ ] ; then
      # there are currently no users in this group
      rm -f  "${TMPFILE}"
      exit
   fi
   TMPFILE2=`tempfile`
   for user in "${USERS}" ; do
      grep -w "$user" "$TMPFILE" >> "$TMPFILE2"
   done
   mv "$TMPFILE2" "$TMPFILE"
fi

if [ $COMMA -eq 1 ] ; then
  sort -u "${TMPFILE}" | tr '\n' ',' \
     | sed 's/,/&\ /g' | sed 's/, *$//g'
else
  sort -u "${TMPFILE}"
fi

rm -f "${TMPFILE}"
