#!/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 rename existing group in agent machines.
#
# ARGUMENT(S):
#
#  1) To rename existing group
#
#       ARGUMENT FORMAT: <new_group_name> <old_group_name>
#       EXAMPLE        : newgroup oldgroup

#           RETURN VALUE                  MEANING

#                0             Groupname changed successfully
#                1             Error while renaming
#                2             Invalid arguments.

errorCode=2

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

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

  errorCode=0
  newName=$1
  oldName=$2

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

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

  #change the groupname
  groupmod -n $newName $oldName

  if [ $? -eq 0 ]; then
    echo "Group: \"$oldName\" changed to \"$newName\" successfully"
  else
    echo "Error while renaming : $oldUserName"
    errorCode=1
  fi
done

errorFunc() {
  return $errorCode
}
errorFunc
