#!/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 file or directory within agent machines.
#
# ARGUMENT(S):
#
#  1) To rename the given file
#
#       ARGUMENT FORMAT: <old_filename_path_in_agent_machine> <new_filename>
#       EXAMPLE        : /home/user/old/fileold filenew

#           RETURN VALUE                  MEANING

#                0             Renamed the given files sucessfully.
#                1             Error while renaming the file/ directory.
#                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 root access
  if [ $euid -ne 0 ]; then
    echo "This script must be run as root"
    break
  fi

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

  errorCode=0
  sourcePath=$1
  sourcePath=$(readlink -f "$sourcePath")
  sourceName=$(echo $sourcePath | sed 's/\(.*\)\/\(.*\)/\2/')
  newName=$2

  path=$(echo $sourcePath | sed 's/\(.*\)\/.*/\1/')
  newPath=$path\/$newName
  mv -f $sourcePath $newPath

  if [ $? -eq 0 ]; then
    echo "Oldfile \"$sourceName\" renamed successfully"
  else
    echo "Error while renaming the given file"
    errorCode=1
  fi
done

errorFunc() {
  return $errorCode
}
errorFunc
