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

# Delete a user.
# Takes the account name (short name) and:
#   removes the user from all groups
#   removes the user's primary group (of the same name)
#   removes the user's account in NetInfo
#   archives and deletes the user's home directory in /Users/shortname

commandname=$0

declare user  # to hold user's account name
declare str   # working


function usage {
  print "Delete a user account, group, and group membership"
  print "Usage: $commandname username"
  if [[ "$*" != "" ]]; then 
     print ""
     print "Error: $*"
  fi
  return 1
}

# Check parameters
#
if [[ $# -ne 1 ]]; then
  usage
  return 21
fi

user="$1"
RecordName=${user}

# search Directory Service for the given user - it should exist
str="$(dscl . -list /Users  |  grep -w $RecordName )"
if [[  -z "$str" ]]; then
  usage "User $user does not exist"
  return 1
fi

# Delete the user from Directory Services
#
# delete the user from all groups

autoload -U remove_user_from_group
remove_user_from_group all $user

# delete the user's primary group
autoload -U delete_group
delete_group -q $user

# delete the user from NetInfo
sudo dscl . delete /users/$user

print "User $user deleted"

# Archive the user's home directory
#
# check that the user has a home directory
if [[ -d /Users/$user ]]; then
  # archive it
  cd /Users
  sudo /usr/bin/tar -czf ${user}-archive.tgz $user
  cd  
  
  # delete it CHECKING THAT AN ARCHIVE WAS CRESATED
  if [[ -e /Users/${user}-archive.tgz ]]; then
    sudo rm -rf /Users/${user}
  fi
fi

print "Users home directory archived as /Users/${user}-archive.tgz and deleted"

return 0

