#!/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 user(s) in /etc/passwd from group in agent machines.
#
# ARGUMENT(S):
#
#  1) To delete single user group
#
#       ARGUMENT FORMAT: <group_name> <user_name>
#       EXAMPLE        : mygroup testuser
#
#  2) To delete multiple users group
#
#       ARGUMENT FORMAT: <group_name> <user_name_1> <user_name_2> ...
#       EXAMPLE        : mygroup user1 user2 user3

#           RETURN VALUE                  MEANING

#                0             User(s) deleted from group successfully
#                1             Error while deleting user(s) from group
#                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 number of arguments
  if [ $# -lt 2 ]; then
    echo "Incorrect Usage : Arguments mismatch."
    echo "Refer ARGUMENT(S) section in the script."
    break
  fi

  errorCode=0
  groupName=$1

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

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

  #check given username are valid and they are present in the groups
  shift
  for i in $@; do
    IsUser=$(grep -c '^'$i':' /etc/passwd)
    if [ $IsUser -eq 0 ]; then
      inValUser="$inValUser""$i""," #store invalid usernames
    else
      IsGrpUsr=$(getent group | grep -c -E '^'$groupName':.*'$i'$|^'$groupName':.*'$i',')
      if [ $IsGrpUsr -eq 1 ]; then
        gpasswd -d $i $groupName            #remove the user from the group
        removed_user="$removed_user""$i""," #store removed usernames list
      else
        non_member_user="$non_member_user""$i""," #store valid users and they are not present in the group
      fi
    fi

  done

  non_member_user=$(echo $non_member_user | sed 's/,$//')
  inValUser=$(echo $inValUser | sed 's/,$//')
  removed_user=$(echo $removed_user | sed 's/,$//')

  if [ $? -eq 0 ]; then
    if [ "$removed_user" ]; then
      echo "User(s): \"$removed_user\" deleted from group \"$groupName\" successfully"
    fi
    if [ "$inValUser" ]; then
      echo "User(s) does not exist in /etc/passwd : $inValUser"
    fi
    if [ "$non_member_user" ]; then
      echo "User(s) who don't exist in the group \"$groupName\" : \"$non_member_user\" "
    fi
  else
    echo "Error while deleting user(s) from the group $groupName"
    errorCode=1
  fi
done

errorFunc() {
  return $errorCode
}
errorFunc
