#!/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
 

# Remove a user from a group, or all groups
# Removes an existing user from an existing group in NetInfo, or from
#  all groups to which that user belongs (but not their primary group)

declare groups  # hold the given group name or the list of groups
declare user    # hold the user account name
declare gid     # hold the group id derived from the group name
declare str strgroup stringroup strprimary  # working

thiscommand=$0

function usage {
  echo "Remove a user from a group or all groups"
  echo "Usage: $thiscommand group|all user"
  echo "       for 'all' the user is removed from all but their primary group"
  if [[ "$*" != "" ]]; then echo; echo "Error: $*"; fi
  return 1
}

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

groups="$1"; user="$2"

# If group is all, expand into the list of groups to which the user belongs
#
if [[ $groups = "all" ]]; then
  groups="$(id -Gnr $user)"
fi

# Loop to remove the user from each group
#
for group in $groups; do

  # get the group number from the name
  gid="$(dscl . -list /Groups PrimaryGroupID | grep -w "^$group" |  awk '{print $2}' )"
  
  # check if the group exists
  # strgroup="$(nifind /groups/$group .)"
  strgroup="$( dscl . -list /Groups | grep -w $group )"
  # check if the user is listed for the group (not listed in own primary)
  # stringroup="$(nireport . /groups name users | grep -w "^$group" | grep -w "$user")"
  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 group exists...
  if [[ -z "$strgroup" ]]; then
    echo "Group $group does not exist"
  # ...and this is not the user's primary group
  elif [ ! -z "$strprimary" ]; then
    echo "Not removing from primary group $group"
  # ...and that the user is listed in the group
  elif [ -z "$stringroup" ]; then
    echo "User $user not listed in $group"
  else
    # remove user from the group

    sudo dscl . delete /groups/$group users $user
    echo "User $user removed from group $group"
  fi
done

return 0

