#!/bin/bash

# DISCLAIMER   :   It is recomended to test this script on a test machine.
#                  ManageEngine will not be responsible for any
#                  damage/loss to the data/setup based on the behavior of the script.

# DESCRIPTION  :   Script to delete existing group in agent machines.
#
# ARGUMENT(S):
#
#  1) To delete group
#
#       ARGUMENT FORMAT: <group_name_to_be_deleted>
#       EXAMPLE        : mygroup

#           RETURN VALUE                  MEANING

#                0             Group deleted successfully
#                1             Error while deleting group
#                2             Invalid arguments.

errorCode=2

euid=$(id -u)
for i in 1; do
  #check sudo access
  if [ $euid -ne 0 ]; then
    echo "This script must be run as root"
    break
  fi

  #check if given arguments are valid
  if [ $# -ne 1 ]; then
    echo "Incorrect Usage : Arguments mismatch."
    echo "Refer ARGUMENT(S) section in the script."
    break
  fi

  errorCode=0
  groupName=$1

  #check group exist or not
  IsGrp=$(getent group | grep -c '^'$groupName':')

  if [ $IsGrp -eq 0 ]; then
    echo "Group : $groupName does not exist "
    break
  fi

  #remove the group
  groupdel $groupName

  if [ $? -eq 0 ]; then
    echo "Group: $groupName deleted successfully"
  else
    echo "Error while deleting group : $groupName"
    errorCode=1
  fi
done

errorFunc() {
  return $errorCode
}
errorFunc
