#!/bin/zsh -f

version="2.0.0"

# The script must be run as an admin user 
#
if [[ -z $(/usr/bin/id -p $USER | grep admin) ]];then
	print "You must be an administrative user with sudo privileges in order to run $0"
fi

# For 10.5:  Eliminated niutil commands in favor of Directory Service
# Obtained and modified from a bash shell script available at
# http://www.osxfaq.com/tips/unix-tricks/week91/friday.ws

# Add new users to a an existing group.
# Adds a user (or many users) to an existing group in NetInfo

declare group user  # hold the given group name and user account name
declare gid         # hold the group id derived from the group name
declare str struser stringroup strprimary  # working

commandissued=$0

function usage {
  print "Add a user (or several users) to an existing group"
  print "Usage: $commandissued group user [user...]"
  if [[ "$*" != "" ]]; then echo; echo "Error: $*"; fi
  return 1
}

# Check parameters
#
if [[ $# -lt 2 ]]; then
  usage
  return 1
fi

group="$1"

# search Directory Service for the given group - it should exist

str="$( dscl . -list /Groups | grep -w $group )"
if [[ -z "$str" ]]; then
  usage "Group $group does not exist"
  return 11
fi

# get the group number from the name
gid="$(dscl . -list /Groups PrimaryGroupID | grep -w "^$group" |  awk '{print $2}' )"


# Drop the group and loop through additional parameters (users) to add to group
#
shift

for user in $*; do
  # check if the user exists
  # struser="$(nifind /users/$user .)"
  struser="$(dscl . -list /Users  |  grep -w $user )"  
  # check if the user already belongs to the group
  stringroup="$( dscl . -list /Groups users | grep -w "^$group" | grep -w "$user")"
  # check if this is the user's primary group
  strprimary="$(dscl . -list /Groups PrimaryGroupID | grep -w "^$user" | grep -w "$gid" )"

  # ensure that the user exists...
  if [[ -z "$struser" ]]; then
    echo "User $user does not exist"
  # ...and does not already belong to the group...
  elif [[ ! -z "$stringroup" ]]; then
    echo "User $user already belongs to group $group - not added again"
  # ...and this is not the user's primary group
  elif [[ ! -z "$strprimary" ]]; then
    echo "This is the user's primary group - not added"
  else
    # add user to the group
    sudo dscl . merge /groups/$group users "$user" 
    echo "User $user added to group $group"
  fi
done

return 0

