#!/bin/sh

## RADIUS Configuration Check for RSA SecurID Appliance   ##


# Variables used by this shell script
RSADIR=/opt/rsa/am

# Filename for the log file
LOGFILENAME=rsa_am_preupgrade_check_`date "+%Y.%m.%d-%H.%M.%S"`.log
LOGFILE=$RSADIR/radius-migration/$LOGFILENAME

# OC credentials
OCADMIN=""
OCPASSWD=""

#CLU variables
componentDir=$RSADIR"/utils/rsa-am-pre-upgrade-check-2.1"
sourceJar=$RSADIR"/utils/rsa-am-pre-upgrade-check-2.1/am-sbr-migration*.jar" 
destinationJar=$RSADIR"/utils/lib/am-sbr-migration.jar"
radiusRootPath=$RSADIR"/radius/ROOT"
originalRadVbso=$RSADIR"/radius/system/lib/radVdb.so"
backupRadVbso=$RSADIR"/radius/system/lib/radVdb.so_backup"
newRadVdbSo=$RSADIR"/utils/rsa-am-pre-upgrade-check-2.1/radVdb.so"


#
#Use to log the error message with exit execution
#
error_exit()
{
    echo -e "\nError: $1\n"  2>&1 | tee -a  "${LOGFILE}"
    exit 1
}

#
#Check the status of the command and log the error
#
command_execution_status()
{
	if [ "$1" != "0" ]; then
		error_exit "$2"
	fi
}
#
# Setting up the log file
#
log_file_setup () {

	if [ -f $LOGFILE ]; then
	        rm -rf $LOGFILE
	fi

        touch $LOGFILE
}

#
# Display log filename
#
display_log_filename () {
	newLogLocation=$(ls -td $RSADIR/radius-migration/*/ | head -1)$LOGFILENAME
	if [ -f $LOGFILE ]; then
		echo -e "\nLog File : "$newLogLocation
		echo -e "\nDone!\n" 2>&1 | tee -a  "${LOGFILE}"
	else
		echo -e "\nLog file does not exist yet!"
	fi	

	mv $LOGFILE $newLogLocation
}

#
# Program Title
#
program_title () {

	clear
	if [ ! -d "/opt/rsa/am/radius-migration/" ]; then
		mkdir "/opt/rsa/am/radius-migration/"
	fi
	echo -e "\n--------------------------------------------------------------------------------------------------\n" 2>&1 | tee -a  "${LOGFILE}"
	echo -e "\n                 Authentication Manager 8.6 Pre Upgrade RADIUS Configuration Check " 2>&1 | tee -a  "${LOGFILE}"
	echo -e "\n--------------------------------------------------------------------------------------------------\n" 2>&1 | tee -a  "${LOGFILE}"
	echo -e "\n This script will trigger the Pre-Migration Check CLU Action and generate an html report at the end." 2>&1 | tee -a  "${LOGFILE}"
	echo -e "\n©1994-2022 RSA Security LLC or its affiliates. All rights reserved." 2>&1 | tee -a  "${LOGFILE}"
	echo -e "\n---------------------------------------------------------------------------------------------------\n" 2>&1 | tee -a  "${LOGFILE}"
}

#
# Prompt for Operations Console (OC) credentials
#
prompt_OC_credentials () {

	echo -n "Please enter OC Administrator username: " 2>&1 | tee -a  "${LOGFILE}"
	read OCADMIN
	if [ "$OCADMIN" = "" ]; then 
		error_exit "Incorrect OC Administrator username provided"
	fi
	
	echo -n "Please enter OC Administrator password: " 2>&1 | tee -a  "${LOGFILE}"
	read -s OCPASSWD
	if [[ "$OCPASSWD" = "" ]]; then
		error_exit "Incorrect OC Administrator password provided"
	fi
}

#
# Check the user account using the shell script - Must be rsaadmin
#
user_check () {
	u=`id 2>/dev/null | cut -d'(' -f2 | cut -d')' -f1`

	if [ "$u" != "rsaadmin" ]; then
		error_exit "you must login with "rsaadmin" user to use this program, Exiting !"
	fi
}

#
# Looking up the authentication manager database password for rsa_user (providing the OC credentials are correct)
#
rsa_user_password () {
	user_check
	USER=$u

	CLU_USER_LINE=`cat $RSADIR/utils/rsaenv | grep CLU_USER= | cut -d'=' -f2`
	CLU_U=`echo $CLU_USER_LINE | cut -d\" -f 2`

	if [ "$USER" == "$CLU_U" ]; then
	    STRG=`/opt/rsa/am/utils/rsautil manage-secrets -a get com.rsa.db.user.password -u $OCADMIN -p $OCPASSWD`
	    if [ "$?" != "0" ]; then
			error_exit "OC credentials provided were invalid, Exiting..."
	    else 
	    	echo -e "\nOC credentials confirmed!" 2>&1 | tee -a  "${LOGFILE}"
			sudo chmod -R 777 $radiusRootPath
			if [ "$?" != "0" ]; then
				error_exit "$USER credentials provided were invalid, Exiting..."
			else 
				echo -e "\n$USER credentials confirmed!" 2>&1 | tee -a  "${LOGFILE}"
			fi
	    fi
	fi
}


#
# AM Version Check
#
am_ver_check () {
	FULLVER=`awk '{print $4}' /etc/issue`
	VER=`echo $FULLVER | awk -F- '{print $1}'`
	
	echo -e "\nAM version found : "$VER 2>&1 | tee -a  "${LOGFILE}"
	
	if [[ $VER != *"8.5"* ]]; then
		error_exit "Incorrect AM version, This script can be executed only on AM 8.5.x, Exiting program...!"
	fi	
}

#
# Validation check for present working directory as rsa-am-pre-upgrade-check-2.1
#
script_cur_dir_check () {
	if [ $PWD == $componentDir ]; then
		echo -e "\nCurrent directory $componentDir \n" 2>&1 | tee -a  "${LOGFILE}"
	else
		error_exit "Incorrect directory. Please execute script from $componentDir directory. Exiting program...!"
	fi	
}

#
# Validation check for components - am-sbr-migration*.jar, radVdb.so with absolute path.
#
script_resource_check () {
	if [ -f $sourceJar ]; then
		echo -e "\nFile $sourceJar exists. continuing program...! \n" 2>&1 | tee -a  "${LOGFILE}"
	else
		error_exit "File $sourceJar doesn't exist. Exiting program...!\nPlease ensure am-sbr-migration-2.1.jar should present under $componentDir"
	fi

	if [ -f $newRadVdbSo ]; then
		echo -e "\nFile $newRadVdbSo exists. continuing program...! \n" 2>&1 | tee -a  "${LOGFILE}"
	else
		error_exit "File $newRadVdbSo does not exist. Exiting program...! \nPlease ensure radVdb.so should be present under $componentDir"
	fi
}

#
# Validation check and Backing up  radVb.so file before CLU operation.
#
am_radvbso_file_backup () {
	if [ -f $originalRadVbso ];then
			radVdbfileSize=`ls -l $originalRadVbso | cut -d " " -f5`
			echo -e "\nOriginal radVdb.so size is : $radVdbfileSize\n" 2>&1 | tee -a  "${LOGFILE}"
			if [ ! -f $backupRadVbso ];then
				echo -e "\nBacking up radVdb.so file" 2>&1 | tee -a  "${LOGFILE}"
				cp $originalRadVbso $backupRadVbso
				command_execution_status $? "Attempt to take back-up radVdb.so file failed" 
				echo -e "\nCopied $originalRadVbso to $backupRadVbso backup file\n" 2>&1 | tee -a  "${LOGFILE}"
			fi 
	else
			error_exit "File $originalRadVbso does not exist. Exiting program...!"
	fi
}


#
# Setting up
#
am_sbr_migration_check_pre_requisite () {
	cp $sourceJar $destinationJar
	command_execution_status $? "Failed to copy $sourceJar to $destinationJar"
	cp $newRadVdbSo $originalRadVbso 
	command_execution_status $? "Failed to copy $newRadVdbSo to $originalRadVbso"
	$RSADIR/server/rsaserv restart radius 2>&1 | tee -a  "${LOGFILE}"
}


#
# Reverting back env back to previous state of script execution
#
am_sbr_migration_check_post_requisite () {
	echo -e "\nRemoving jar artifacts" 2>&1 | tee -a  "${LOGFILE}"
	rm $destinationJar 2>&1 | tee -a  "${LOGFILE}"
	echo -e "\nReverting radVdb.so file" 2>&1 | tee -a  "${LOGFILE}"
	cp $backupRadVbso $originalRadVbso
	if [ "$?" != "0" ]; then
		echo -e "\n Error: Failed to revert radVdb.so file. Replace the <$backupRadVbso> to <$originalRadVbso> manually and restart the radius server" 2>&1 | tee -a  "${LOGFILE}"
	else
		radVdbfileSize=`ls -l $originalRadVbso | cut -d " " -f5`
		echo -e "\nReverted back radVdb.so size is : $radVdbfileSize\n" 2>&1 | tee -a  "${LOGFILE}"
	fi
	
	$RSADIR/utils/rsautil --generate-classpath 2>&1 | tee -a  "${LOGFILE}"
	$RSADIR/server/rsaserv restart radius 2>&1 | tee -a  "${LOGFILE}"
}


#
# Log file and reporting information
#
script_log_end (){
	rm -r $RSADIR"/utils/rsa-am-pre-upgrade-check-2.1/logs"
	newLogLocation=$(ls -td $RSADIR/radius-migration/*/ | head -1)
	echo -e "\n-------------------------------------------------------------------------------------------------------------" 2>&1 | tee -a  "${LOGFILE}"
	echo -e "\nPlease check the below report for more details." 2>&1 | tee -a  "${LOGFILE}"
	echo -e "\nThe RSA RADIUS Pre-Migration Report (radius-pre-migration-check-report.html) is available in ${newLogLocation}" 2>&1 | tee -a  "${LOGFILE}"
	echo -e "\n-------------------------------------------------------------------------------------------------------------" 2>&1 | tee -a  "${LOGFILE}"
}



#
# Trigger CLU Action's 
#
trigger_clu_action() {

	#backup
	am_radvbso_file_backup

	#Setup
	am_sbr_migration_check_pre_requisite

	#execution
	$RSADIR/utils/rsautil --generate-classpath  2>&1 | tee -a  "${LOGFILE}"
	$RSADIR/utils/rsautil am-sbr-migration -a premigrate  2>&1 | tee -a  "${LOGFILE}"

	#Revert
	am_sbr_migration_check_post_requisite

	#Reporting
	script_log_end

}


## Main Body

program_title
user_check
script_cur_dir_check
script_resource_check
am_ver_check
prompt_OC_credentials
rsa_user_password
trigger_clu_action
display_log_filename