#!/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 Edit the existing local username in linux agent machines.
#
# ARGUMENT(S):
#  1) User for whom name should be renamed.
#
#         ARGUMENT FORMAT: <new_user_name> <old_user_name>
#         EXAMPLE        : newtest oldtest
#
#           RETURN VALUE                  MEANING
#
#                0             Username changed successfully.
#                1             Error while renaming.
#                2             Invalid arguments.

# NOTE :
#   To see the script output, Kindly enable the option Enable logging in Troubleshooting while deploying configuration.

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

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

  errorCode=0
  newUserName=$1
  oldUserName=$2

  #check given username exist or not
  IsUser=$(grep -c '^'$oldUserName':' /etc/passwd)

  if [ $IsUser -eq 0 ]; then
    echo "UserName : $oldUserName does not exist"
    errorCode=1
    break
  fi

  pkill -9 -u $oldUserName
  killall -u $oldUserName
  usermod -l $newUserName $oldUserName
  usermod -d /home/$newUserName -m $newUserName

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

errorFunc() {
  return $errorCode
}
errorFunc
