#!/bin/ksh93
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
# perf72L src/perf/pmaix/usr/bin/pmcfg/config_pm_ext.sh 1.13.1.1 
#  
# Licensed Materials - Property of IBM 
#  
# Restricted Materials of IBM 
#  
# COPYRIGHT International Business Machines Corp. 2012,2018 
# All Rights Reserved 
#  
# US Government Users Restricted Rights - Use, duplication or 
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp. 
#  
# IBM_PROLOG_END_TAG 
# @(#)09	1.8.5.5  src/perf/cmdperft/usr/bin/pmcfg/config_pm_ext.sh, PMAIX, perf71H 8/13/12 02:06:40

# check if /var/perf/pm/bin/pmcfg_ext script exists ,if it exists then
# Update "# PMExt:1" with "# PMExt:2" string in /var/perf/pm/config/pmconf 
# if this entry doesn't exist already. 

SetPMExt()
{
	#check for "# PMExt:2" string in pmconf file to check
	#if /var/perf/pm/bin/pmcfg_ext existence is already checked.
	/usr/bin/grep "# PMExt:2" ${PMCONF} > /dev/null 2>&1
	rc=$?
	if [[ $rc -ne 0 ]]
	then
		PMCFG_EXT=/var/perf/pm/bin/pmcfg_ext
		#add "# PMExt:2" to end of pmconf file
		# if pm transmission is enabled .
		if [[ -f ${PMCFG_EXT} ]]
		then
			/usr/bin/sed "s/# PMExt:.*/# PMExt:2/" ${PMCONF} > /tmp/_pmconf
			if [ $? -eq 0 ]
			then
				/usr/bin/cp /tmp/_pmconf ${PMCONF}
				if [[ $? -eq 0 ]]
				then
					echo $(dspmsg pm_ext.cat -s 1 13 'pmcfg extension script available' )
				fi
			fi
			/usr/bin/rm -f /tmp/_pmconf
		else
			echo $(dspmsg pm_ext.cat -s 1 11 'pmcfg extension script is not available' )
		fi
	fi
}

UnsetPMExt()
{
	#check for "# PMExt:2" string in pmconf file to check
	#if pm transmission is enabled. Update this entry to "# PMExt:1"
	/usr/bin/grep "# PMExt:2" ${PMCONF} > /dev/null 2>&1
	rc=$?
	if [[ $rc -eq 0 ]]
	then
		/usr/bin/sed "s/# PMExt:.*/# PMExt:1/" ${PMCONF} > /tmp/_pmconf
		if [ $? -eq 0 ]
		then
			/usr/bin/cp /tmp/_pmconf ${PMCONF}
			if [[ $? -eq 0 ]]
			then
				echo $(dspmsg pm_ext.cat -s 1 14 'Successfully disabled Extended functionality of pmcfg' )
			else
				echo $(dspmsg pm_ext.cat -s 1 15 'Error: Not able to disable Extended functionality of pmcfg.' )
			fi
		fi
			
		/usr/bin/rm -f /tmp/_pmconf
	fi
}


SetXlparInterval()
{
	Xlpar_Interval=$*
	PMCONF=/var/perf/pm/config/pmconf
	
	HwType=`/usr/sbin/getsystype -i | /usr/bin/awk '{print $2}' 2>/dev/null`
	
	val=`/usr/bin/grep Xlpar_Interval ${PMCONF}`
	if [[ $? -ne 0 ]]; then
		/usr/bin/cat ${PMCONF} > /tmp/_pmconf
		echo >> /tmp/_pmconf
		echo '# Cross Lpar Interval' >> /tmp/_pmconf
		echo "Xlpar_Interval:" >> /tmp/_pmconf
		echo >> /tmp/_pmconf
		/usr/bin/cp /tmp/_pmconf ${PMCONF}
	fi
	
	/usr/bin/sed "s/Xlpar_Interval:.*/Xlpar_Interval:${Xlpar_Interval}/" ${PMCONF} > /tmp/_pmconf
	/usr/bin/cp /tmp/_pmconf ${PMCONF}
	/usr/bin/rm /tmp/_pmconf
	val=`/usr/bin/grep Xlpar_Interval ${PMCONF}`
	if [[ $? -eq 0 ]]; then
		echo $(dspmsg pm_ext.cat -s 1 8 'Successfully updated Cross Lpar Interval ')
	else
		echo $(dspmsg pm_ext.cat -s 1 9 'Failed to update Cross Lpar Interval ')
		exit 1
	fi
	
	TMP_CRON=/tmp/_Crontab_Pm
	
	# Delete all the entries related to pmcfg_ext -C
	/usr/bin/crontab -l | /usr/bin/grep "pmcfg_ext -C" >/dev/null 2>&1
	if [[ $? -eq 0 ]]
	then
		#Delete the crontab entry
		/usr/bin/crontab -l | /usr/bin/grep -v "pmcfg_ext -C" > $TMP_CRON
		if [[ $? -ne 0 ]]
		then
			echo "Failed to create a temporary crontab file"
			exit 1
		fi
		
		/usr/bin/crontab $TMP_CRON
		if [[ $? -ne 0 ]]
		then
			echo "Failed to update crontab "
			exit 1
		fi
		
		# Clean the file
		/usr/bin/rm -f 	$TMP_CRON
		# Exit if requested to Disable Xlpar collection 
		if [[ ${Xlpar_Interval} -eq 0 ]]
		then
			return
		fi
	fi
	
	
	# Add new pmcfg crontab entries
	/usr/bin/crontab -l > $TMP_CRON
	if [[ $? -ne 0 ]]
	then
		echo "Failed to copy crontab to temporary file"
		
		exit 1
	fi
	
	
	PMCONF=/var/perf/pm/config/pmconf
	if [[ -f ${PMCONF} ]] 
	then
		Xlpar_Interval=`/usr/bin/grep Xlpar_Interval ${PMCONF} | /usr/bin/cut -d ':' -f 2-10 | /usr/bin/sed 's/:/#!:/g'`
	fi
	
	# If its lower than POWER 8, remove # XlparEnabled entry to pmconf file
	val=`/usr/bin/grep '# XlparEnabled' ${PMCONF}`
	if [[ $? -eq 0 ]]; then
		/usr/bin/grep -v '# XlparEnabled' ${PMCONF} > /tmp/_pmconf_$$
		/usr/bin/cp /tmp/_pmconf_$$ ${PMCONF}
	fi
	
	# Add the pmcfg -C entry to crontab only if hardware is greater than POWER 7
	if [[ ${HwType} -gt 7 ]]; then
		
		# If its POWER 8, add # XlparEnabled entry to pmconf file
		val=`/usr/bin/grep '# XlparEnabled' ${PMCONF}`
		if [[ $? -ne 0 && ! -z ${Xlpar_Interval} ]]; then
			/usr/bin/cat ${PMCONF} > /tmp/_pmconf_$$
			/usr/bin/sed '/\#\ Cross Lpar Interval/a\
\#\ XlparEnabled' ${PMCONF} >/tmp/_pmconf_$$
			/usr/bin/cp /tmp/_pmconf_$$ ${PMCONF}
		fi
		
	else
	
		if [[ ${Xlpar_Interval} -eq 1440 ]]; then
			/usr/bin/cat <<EOF >>$TMP_CRON
0 0 * * * /var/perf/pm/bin/pmcfg_ext -C  >/dev/null 2>&1     #Cross Lpar
EOF
		elif [[ ${Xlpar_Interval} -eq 720 ]]; then
			/usr/bin/cat <<EOF >>$TMP_CRON
0 0,12 * * * /var/perf/pm/bin/pmcfg_ext -C  >/dev/null 2>&1     #Cross Lpar
EOF
		elif [[ ${Xlpar_Interval} -eq 360 ]]; then
			/usr/bin/cat <<EOF >>$TMP_CRON
0 0,6,12,18 * * * /var/perf/pm/bin/pmcfg_ext -C  >/dev/null 2>&1     #Cross Lpar
EOF
		elif [[ ${Xlpar_Interval} -eq 120 ]]; then
			/usr/bin/cat <<EOF >>$TMP_CRON
0 0,2,4,6,8,10,12,14,16,18,20,22 * * * /var/perf/pm/bin/pmcfg_ext -C  >/dev/null 2>&1     #Cross Lpar
EOF
		elif [[ ${Xlpar_Interval} -eq 60 ]]; then
			/usr/bin/cat <<EOF >>$TMP_CRON
0 * * * * /var/perf/pm/bin/pmcfg_ext -C  >/dev/null 2>&1     #Cross Lpar
EOF
		elif [[ ${Xlpar_Interval} -eq 30 ]]; then
			/usr/bin/cat <<EOF >>$TMP_CRON
0,30 * * * * /var/perf/pm/bin/pmcfg_ext -C  >/dev/null 2>&1     #Cross Lpar
EOF
		elif [[ ${Xlpar_Interval} -eq 15 ]]; then
			/usr/bin/cat <<EOF >>$TMP_CRON
0,15,30,45 * * * * /var/perf/pm/bin/pmcfg_ext -C  >/dev/null 2>&1     #Cross Lpar
EOF
		fi
	fi
		
	if [[ $? -ne 0 ]]
	then
		echo "Failed to create a new copy of crontab."
		exit 1
	fi
		
	# Update the real cron file
	/usr/bin/crontab $TMP_CRON
	if [[ $? -ne 0 ]]
	then
		echo "Failed to update crontab."
		exit 1
	fi
	/usr/bin/rm -f ${TMP_CRON}
		
}

GetXlparInterval()
{
	PMCONF=/var/perf/pm/config/pmconf
	if [[ -f ${PMCONF} ]] 
	then
		Xlpar_Interval=`/usr/bin/grep Xlpar_Interval ${PMCONF} | /usr/bin/cut -d ':' -f 2-10 | /usr/bin/sed 's/:/#!:/g'`
	fi
	
	echo "#Xlpar Interval:"
	echo "${Xlpar_Interval}:"
}


CleanUpTmpFiles()
{
	TmpFile1=$1
	
	## If temp file is present, remove the file
	if [[ -e ${TmpFile1} ]]; then
		/usr/bin/rm ${TmpFile1}
	fi
	
}


SetPasswordLessSSH()
{
	#set -x
	
	PMCONF=/var/perf/pm/config/pmconf
	
	tty >/dev/null;
	
	## Get the HMC Name and User Name from the arguments passed
	Hmc_Name_New=`echo $1 | grep HMCNAM | cut -d'=' -f2`
	Hmc_User_New=`echo $2 | grep HMCUSER | cut -d'=' -f2`
	
	## HscPass set to 0 if hscroot has password-less SSH configured, and UserPass to 0 if User ID has password-less SSH configured
	HscRootPass=0
	UserPass=0
	ConfiguredNewSSH=0
	UnconfigureOldSSH=0
	
	ExitStatus=0
	Hmc_User_New=""
	if [[ ${Hmc_Name_New} != "" ]]; then
		Hmc_User_New="pmaixusr"
	fi
	
	ReturnSuccess=0
	HostName=`hostname`
	Hmc_P_PM=""
	
	Result=""
	ErrMsg="\nFailed to configure password-less SSH to $Hmc_User_New@$Hmc_Name_New"
	
	TmpFile1="/tmp/temp_auth_$$"
	TmpFile2="/tmp/temp_auth_$$_2"
	
	OldDir=`/usr/bin/pwd`
	UserID=`/usr/bin/id | /usr/bin/cut -d'(' -f2 | /usr/bin/cut -d')' -f1 2>/dev/null`
	HomeDir=`/usr/bin/grep "^$UserID:" /etc/passwd | /usr/bin/cut -d":" -f6 2>/dev/null`
		
	## Get old Hmc Name and Hmc User id, previously configured in pmconf file
	Hmc_Name_Old=`/usr/bin/grep Hmc_Name_PM ${PMCONF} | /usr/bin/cut -d':' -f2`
	Hmc_User_Old=`/usr/bin/grep Hmc_User_PM ${PMCONF} | /usr/bin/cut -d':' -f2`
	
	## If Old HMC info is configured, set flag to unconfigure it
	if [[ ${Hmc_Name_Old} != "" && ${Hmc_User_Old} != "" ]]; then
		
		if [[ ${Hmc_Name_New} == "" || ${Hmc_Name_New} != ${Hmc_Name_Old} || ${Hmc_User_New} != ${Hmc_User_Old} ]]; then
			UnconfigureOldSSH=1
		fi
			
	fi
	
	## Block to Configure password-less SSH 
	## Configure Password-less SSH for new HMC if new hmc name and user id are not blank
	DoWhile=1
	while [[ ${DoWhile} -eq 1 ]]; do
	if [[ ${Hmc_Name_New} != "" && ${Hmc_User_New} != "" ]]; then
		
		## Check if ${Hmc_User_New} has password-less SSH already, if yes, set UserPass=1
		/usr/bin/ssh -o ConnectTimeout=10 -o 'PreferredAuthentications=publickey' -o 'StrictHostKeyChecking=no' -l ${Hmc_User_New} ${Hmc_Name_New} echo 2>/dev/null >/dev/null
		
		if [[ $? -eq 0 ]]; then
			UserPass=1
		fi
		
		## Check if hscroot has password-less SSH already, if yes, set HscRootPass=0
		retexpt=`/usr/bin/ssh -o ConnectTimeout=10 -o 'PreferredAuthentications=publickey' -o 'StrictHostKeyChecking=no' -l hscroot ${Hmc_Name_New} echo 2>&1`
		if [[ $? -eq 0 ]]
		then
			## If hscroot id does not prompt for password on SSH to hmc, set HscRootPass to 1
			HscRootPass=1
		else
			## If returned error is for permission, prompt for for hscroot password
			echo $retexpt | grep -i "permission denied" 2>/dev/null >/dev/null
			if [[ $? -eq 0 ]]
			then
				print "\nADMIN PASSWORD:\nPlease enter the password, when prompted, for hscroot@${Hmc_Name_New}:" 
			
			else
				print "SSH to hscroot@${Hmc_Name_New} failed with error:\n${retexpt}"
			fi
		fi
		
		## Get the LPAR Name
		LparName=`lparstat -i | grep "Partition Name" | awk '{print $4}'`
		
		
		## Remote Command Function return value for lparname and id check 
		## Returns 0 if lpar found in hmc and id exist, 
		## Returns 1 if lpar not found in hmc; 
		## Returns 2 if lpar found in hmc, but no id, 
		## Returns 3 if id exist with non-hmcviewer access; 
		## Returns 4 if hmc is not enabled for utilization data
		## Updated for security check for user id task role as hmcviewer
		
		FuncCmd1="
			FuncRetVal1() 
			{ 
				lnam=\$1; 
				idexist=\$2; 
				srat=\$3; 
				if [[ \$lnam -eq 0 ]]; then 
					if [[ \$srat -ne 0 ]]; then 
						return 4; 
					fi; 
					if [[ \$idexist -eq 0 ]]; then 
						return 0; 
					elif [[ \$idexist -eq 2 ]]; then 
						return 3; 
					else 
						return 2; 
					fi; 
				else 
					return 1; 
				fi; 
			} 
		"
		
		## Remote Command Function to return id creation status
		## It returns 0 if id created, else returns error code while creating id.
		FuncCmd2="
			FuncRetVal2() 
			{ 
				idexist=\$1; 
				if [[ \$idexist -eq 0 ]]; then 
					return 0; 
				else 
					return \$idexist; 
				fi; 
			} 
		"
		
		## Remote command To check if lpar belongs to HMC and if user id exist
		## Updated for security check for user id task role as hmcviewer
		## The for loop tests for each physical machine in HMC
		## lssyscfg -r lpar - command grep for partition name managed by hmc under that physical machine
		## lslparutil -r config - to test if utilization data collection is enabled
		## /etc/passwd - to find if user id pmaixusr exists
		## lshmcusr --filter - checks for pmaixusr taskrole if it exist
		## Then it calls the function to return the status
		RemoteCmd1="
			lnam=\"1\"; 
			idexist=\"1\"; 
			srate=0; 
			${FuncCmd1}; 
			for i in \`lssyscfg -r sys -F name\`; 
			do 
				lssyscfg -r lpar -m \"\${i}\" -F name | grep -i \"^${LparName}\$\"; 
				if [[ \$? -eq 0 ]]; then 
					lnam="0"; 
					srat=\`lslparutil -r config -m \"\${i}\" -F sample_rate\`; 
					if [[ \${srat} -eq 0 ]]; then 
						srate=1; 
						break; 
					fi; 
					grep \"^${Hmc_User_New}:\" /etc/passwd; 
					if [[ \$? -eq 0 ]]; then 
						val=\`lshmcusr --filter \"\"names=${Hmc_User_New}\"\" -F taskrole\`; 
						if [[ \$val != \"hmcviewer\" ]]; then 
							idexist=2; 
						else 
							idexist=\"0\"; 
						fi; 
					fi; 
					break; 
				fi; 
				done; 
				FuncRetVal1 \$lnam \$idexist \$srate;
			"
		
		TryAgain=1
		
		PromptCount=0
		RemoteCmd=$RemoteCmd1
		WhichCmd=1
		
		while [[ ${TryAgain} -eq 1 ]]
		do
		
			## Executing Remote Command
			RetStr=`/usr/bin/ssh -o ConnectTimeout=10 -o 'NumberOfPasswordPrompts=1' -l hscroot ${Hmc_Name_New} $RemoteCmd 2>&1 `
			RetVal=$?
			
			if [[ $RetVal -eq 255 ]]; then
				
				## If User ID or Password is wrong, try 3 times
				if [[ $PromptCount -ge 2 ]]; then
					TryAgain=0
					Result="${Result}\nEither HMC/FSM Name ${Hmc_Name_New} or Password is wrong!\n${ErrMsg}\n"
					Result="${Result}\nError Msg: ${RetStr}\n"
					print "$Result"
					return 1
				fi
				PromptCount=`expr $PromptCount + 1`
			
			elif [[ $RetVal -eq 1 ]]; then
				
				## If first command returned 1, HMC is wrong,
				## If second command returned 1, it failed to create user id pmaixusr
				
				if [[ ${WhichCmd} -eq 1 ]]; then
					Result="${Result}\nWrong HMC/FSM. The HMC/FSM ${Hmc_Name_New} does not manage this lpar ${LparName}. Please enter HMC/FSM name managing lpar ${LparName}!\n${ErrMsg}\n"
				elif [[ ${WhichCmd} -eq 2 ]]; then
					Result="${Result}\nFailed to create new user id ${Hmc_User_New} on HMC/FSM ${Hmc_Name_New}\n${ErrMsg}\n"
				fi
				
				print "$Result"
				TryAgain=0
				CleanUpTmpFiles ${TmpFile1} 
				return 1
			elif [[ $RetVal -eq 2 ]]; then
				
				## If first command returns 2, id does not exist, need to create, so loop back
				if [[ ${WhichCmd} -eq 1 ]]; then
					print ""
					print  "\nNEW USER:\nA new user id ${Hmc_User_New} will be created on HMC/FSM ${Hmc_Name_New} with HMCVIEWER access.\n Please enter the password you desire to set to new id ${Hmc_User_New}.\n "
					print "(password must be atleast 7 characters)\n"
					`tty >/dev/null`
					ExitStatus=1
					FirstPass=1
					tmppass=""
					retry=0
					while [[ ${ExitStatus} -eq 1 ]]; do
						## Set the stty not to display what is being typed while reading password until Enter key is returned
						stty -echo
						read Hmc_P_PM
						## Set back stty to display what is being typed 
						stty echo
						if [[ $? -eq 0 ]]; then
							
							if [[ $FirstPass -eq 1 ]]; then
								
								if [[ ${#Hmc_P_PM} -ge 7 ]]; then
									
									FirstPass=0
									print "Please re-enter the password again\n"
									tmppass=$Hmc_P_PM
								else
									## If the password entered is less than 7 characters, prompt to enter correct password
									retry=`expr $retry + 1`
									print "Invalid password specified. Password cannot be empty or less than 7 characters.\n"
								fi
							else
								if [[ $tmppass == $Hmc_P_PM ]]; then
									ExitStatus=0
								else
									## If password does not match while reconfirming, prompt from beginning.
									print "Password does not match, please try again\n"
									print "Please enter new password for user ${Hmc_User_New}\n"
									Hmc_P_PM=""
									tmppass=""
									FirstPass=1
									retry=`expr $retry + 1`
								fi
							fi
						fi
						
						if [[ $retry -ge 3 ]]; then
							ExitStatus=0
							break
						fi
						
					done
					
					if [[ $tmppass == "" ]]; then	
						Result="${Result}\nFailed to provide password for new user in 3 tries.\nPlease try again\n${ErrMsg}\n"
						TryAgain=0
						print "$Result"
						return 1
					fi
					## Remote command to create new user id on hmc, if previous remote command is successful and id not created
					RemoteCmd2="
						idexist=\"1\";
						${FuncCmd2}; 
						mkhmcusr -u ${Hmc_User_New} -a hmcviewer --passwd ${Hmc_P_PM}; 
						retval=\$?; 
						if [[ \$retval -eq 0 ]]; then 
							idexist=0; 
						else 
							idexist=\$retval; 
						fi; 
						FuncRetVal2 \$idexist; 
					"
				
					RemoteCmd=${RemoteCmd2}
					
					if [[ ${HscRootPass} -eq 0 ]]; then
						print "\nADMIN PASSWORD:\nPlease enter the password for hscroot@${Hmc_Name_New}:"
					fi
					WhichCmd=2
					
				elif [[ ${WhichCmd} -eq 2 ]]; then
					Result="${Result}\nFailed to create new user id ${Hmc_User_New} on HMC/FSM ${Hmc_Name_New}\n${ErrMsg}\n"
					TryAgain=0
					print "$Result"
					CleanUpTmpFiles ${TmpFile1} 
					return 1
				fi
			elif [[ $RetVal -eq 3 ]]; then
				
				## If the user has taskrole other than hmcviewer, exit. Due to security concerns.
				Result="${Result}\nUser ID ${Hmc_User_New} exist but not with HMCVIEWER access.\nPlease set taskrole as hmcviewer for id ${Hmc_User_New} on HMC/FSM and try again!.\n${ErrMsg}\n"
				TryAgain=0
				print "$Result"
				CleanUpTmpFiles ${TmpFile1} 
				return 1
			
			elif [[ $RetVal -eq 4 ]]; then
				
				## If the HMC is not enabled for utilization data
				Result="${Result}\nHMC/FSM ${Hmc_Name_New} is not enable to collect utilization data.\nPlease enable HMC/FSM ${Hmc_Name_New} to collect utilization data.\n${ErrMsg}\n"
				TryAgain=0
				print "$Result"
				CleanUpTmpFiles ${TmpFile1} 
				return 1
				
			elif [[ $RetVal -eq 0 ]]; then
				
				## if command success,
				## If the first command returns 0, lpar and id is correct, end loop
				if [[ ${WhichCmd} -eq 2 ]]; then
					print "\nNew user id ${Hmc_User_New} is created.\nPlease remember the password you have set for this ID."
				else
					Result="${Result}\nUser id ${Hmc_User_New} exist on HMC/FSM ${Hmc_Name_New}.\n"
				fi
				TryAgain=0
			fi
			
			
		done
		
		## If new Hmc name is not blank, and password-less ssh failed for new user on new hmc, configure password-less ssh.
		if [[ ${UserPass} -eq 0 ]]; then
			
			cd $HomeDir/.ssh 2>/dev/null
			
			UseIDFile=0
			if [[ -e $HomeDir/.ssh/id_rsa ]]; then
				
				echo $(ssh-keygen -f $HomeDir/.ssh/id_rsa -y -P '""') ${UserID}@${HostName} > $HomeDir/.ssh/id_rsa.pub 2>/dev/null
				if [[ $? -eq 0 ]]; then
					UseIDFile=1
				fi
			fi
			
			if [[ ${UseIDFile} -eq 0 ]]; then
				
				ssh-keygen -t rsa -f "$HomeDir/.ssh/id_rsa" -N "" >/dev/null 2>/dev/null
				
				if [[ $? -ne 0 ]] then
					## If generating ID RSA files failed, exit.
					Result="${Result}\nFailed in generating RSA key $HomeDir/.ssh/id_rsa\n${ErrMsg}\n"
					print "$Result"
					CleanUpTmpFiles ${TmpFile1} 
					return 1
				fi
			else
				Result="${Result}\nFound RSA key $HomeDir/.ssh/id_rsa\n"
			fi
			
			print "\nUSER PASSWORD:\nPlease enter the password for ${Hmc_User_New}@${Hmc_Name_New}:"
			
			## Copying .ssh/authorized_keys2 from HMC to tmp
			scpval=`/usr/bin/scp -o 'NumberOfPasswordPrompts=3' $HomeDir/.ssh/id_rsa.pub $Hmc_User_New@$Hmc_Name_New:/tmp/id_rsa.pub_$$ 2>&1`
			
			if [[ $? -ne 0 ]] then
				
				Result="${Result}\nError: Unable to copy the public key from lpar to HMC $Hmc_User_New@$Hmc_Name_New !.\n"
				if [[ ${scpval} != "" ]]
				then
					Result="${Result}\nError Msg: ${scpval}\n"
				fi
				print "${Result}"
				CleanUpTmpFiles ${TmpFile1} 
				return 1
			fi
			
			print "\nUSER PASSWORD:\nPlease enter the password, for ${Hmc_User_New}@${Hmc_Name_New}:"
			
			## Update authorized_key2 on HMC
			sshval=`/usr/bin/ssh -o ConnectTimeout=10 -o 'NumberOfPasswordPrompts=1'  $Hmc_User_New@$Hmc_Name_New "mkauthkeys -a \"\\\`cat /tmp/id_rsa.pub_$$\\\`\";rm /tmp/id_rsa.pub_$$" 2>&1`
			
			if [[ $? -ne 0 ]]; then
				Result="${Result}\nToHMC/FSM: Failed to configure password-less SSH to $Hmc_User_New@$Hmc_Name_New\n${ErrMsg}\n"
				if [[ ${sshval} != "" ]]
				then
					Result="${Result}\nError Msg: ${sshval}\n"
				fi
				print "${Result}"
				CleanUpTmpFiles ${TmpFile1} 
				return 1
			fi
			
			## "Testing password-less connection to $Hmc_User_New@$Hmc_Name_New\n"
			/usr/bin/ssh -o ConnectTimeout=10 -o 'PreferredAuthentications=publickey' -o 'StrictHostKeyChecking=no' -l ${Hmc_User_New} ${Hmc_Name_New} echo 2>/dev/null >/dev/null
			
			if [[ $? -eq 0 ]] then
				# Update the pmconf file after configuring password-less SSH to HMC/FSM
				ConfiguredNewSSH=1
				ReturnSuccess=1
				
				Result="${Result}\nSuccessfully configure password-less SSH to $Hmc_User_New@$Hmc_Name_New\n"
			else
				Result="${Result}\nFailed to configure password-less SSH to $Hmc_User_New@$Hmc_Name_New\n${ErrMsg}\n"
			fi
			
		elif [[ ${UserPass} -eq 1 ]]; then
			## In case if the password-less already setup
			Result="${Result}\nPassword-Less SSH is Already Configured For $Hmc_User_New@$Hmc_Name_New\n"
			ReturnSuccess=1
		fi
	elif [[ ${Hmc_Name_New} == "" ]]; then
		print "Are you sure you want to unconfigure (y/n) ?\n"
		Confirm=0
		while [[ $Confirm -eq 0 ]]; do
		read val
		if [[ $val == [yY] ]]; then
			ReturnSuccess=1
			Hmc_User_New=""
			Hmc_Name_New=""
			Confirm=1
		elif [[ $val == [nN] ]]; then
			print "Unconfiguration cancelled!!\n"
			ReturnSuccess=2
			UnconfigureOldSSH=0
			Confirm=1
		else
			print "Enter y or Y to unconfigure else n or N to cancel ?\r"
		fi
		done
	fi
	DoWhile=0
	done
	
	#set -x
	ExitStatus=1
	if [[ ${UnconfigureOldSSH} -eq 1 ]]; then
		
		## Check if public key was configured earlier by this function, if yes, unconfigure
		/usr/bin/grep Public_Key_Configured ${PMCONF} 2>/dev/null >/dev/null
			
		if [[ $? -eq 0 ]]; then
			
			## Unconfigure password-less ssh for old Hmc Info if Old Hmc name is not null
			/usr/bin/ssh -o ConnectTimeout=10 -o 'PreferredAuthentications=publickey' -o 'StrictHostKeyChecking=no' -l ${Hmc_User_Old} ${Hmc_Name_Old} echo 2>/dev/null
		
			if [[ $? -eq 0 ]]; then
				## If configured, remove entry from old Hmc auth file
				`/usr/bin/scp -o 'NumberOfPasswordPrompts=3' $HomeDir/.ssh/id_rsa.pub $Hmc_User_Old@$Hmc_Name_Old:/tmp/id_rsa.pub_$$ 2>/dev/null`
				
				if [[ $? -eq 0 ]] then
					## HMC Command mkauthkeys will update the content of the id_rsa file to authorized key, -r flag will remove the entry from auth file
					sshval=`/usr/bin/ssh -o ConnectTimeout=10 -o 'NumberOfPasswordPrompts=1' $Hmc_User_Old@$Hmc_Name_Old "mkauthkeys -r \"\\\`cat /tmp/id_rsa.pub_$$\\\`\";rm /tmp/id_rsa.pub_$$"  2>&1`
					
					if [[ $? -eq 0 ]]; then
						ExitStatus=0
					else
						Result="${Result}\nFromHMC/FSM: Failed to unconfigure password-less SSH to HMC/FSM $Hmc_User_Old@$Hmc_Name_Old\n"
						if [[ ${sshval} != "" ]]
						then
							Results="${Result}\nError Msg: ${sshval}\n"
						fi
						ExitStatus=1
					fi
				else
					Result="${Result}\nToHMC/FSM: Failed to unconfigure password-less SSH to HMC/FSM $Hmc_User_Old@$Hmc_Name_Old"
					ExitStatus=1
				fi
				
			fi
		if [[ ${ExitStatus} -eq 1 ]]; then
			Result="${Result}\nFailed to unconfigure password-less SSH to HMC/FSM $Hmc_User_Old@$Hmc_Name_Old"
			
		fi
			/usr/bin/grep -v Public_Key_Configured ${PMCONF} > ${TmpFile1} 2>/dev/null
			/usr/bin/cp ${TmpFile1} ${PMCONF} 2>/dev/null
		fi
	fi
	
	if [[ ${ConfiguredNewSSH} -eq 1 ]]; then
		/usr/bin/grep -v Public_Key_Configured ${PMCONF} > ${TmpFile1} 2>/dev/null
		
		if [ $? -eq 0 ]; then
			echo "# Public_Key_Configured" >> ${TmpFile1} 2>/dev/null
			
			if [[ $? -eq 0 ]]; then
				/usr/bin/cp ${TmpFile1} ${PMCONF} 2>/dev/null
			fi
		fi
	fi
	
	print "$Result"
	
	cd ${OldDir}
	
	CleanUpTmpFiles ${TmpFile1} 
	Hmc_User_PM=${Hmc_User_New}
	if [[ ${ReturnSuccess} -eq 1 ]]; then
		return 0
	elif [[ ${ReturnSuccess} -eq 2 ]]; then
		return 2
	else
		return 1
	fi
}


WaitForUserEnter()
{
	print "\n\nHit Enter key to continue..\n"
	read
}


SetHMCInfo()
{
	## Check if SSH is availble, if not, exit with error message
	SSH=`which ssh 2>/dev/null >/dev/null`
	if [[ $? -ne 0 ]]; then
		print "\nError: Unable to find SSH"
		print "Please install SSH first to setup HMC Info and configure Password-Less SSH to HMC"
		WaitForUserEnter
		exit
	fi
	
	PMStatus=`/var/perf/pm/bin/config_pm.sh status`
	if [[ ${PMStatus} == "Disabled" ]]; then
		print "Error: PM data transmission is not enabled.\n"
		print "Please enable PM using SMIT.\n"
		print "====================================
Steps to enable PM
====================================
1. From the command line, type 'smit topas'.
2. Select 'Setup Performance Management'.
3. Select 'Enable Data Transmission' to enable PM data transmission.\n"
		WaitForUserEnter
		exit
	fi
	
	while getopts ':n:u:' option
	do
		case ${option} in
			n)Hmc_Name_PM=${OPTARG} ;;
			u)Hmc_User_PM=${OPTARG} ;;
			[?])exit 1
			;;
		esac
	done
	
	PMCONF=/var/perf/pm/config/pmconf
	
	SSHConfigured=0
	SetPasswordLessSSH HMCNAM=$Hmc_Name_PM HMCUSER=$Hmc_User_PM
	SshVal=$?
	if [[ $SshVal -eq 1 ]]; then
		echo "Unable to configure password-less SSH to new HMC/FSM Information"
		WaitForUserEnter
		exit 
	elif [[ $SshVal -eq 2 ]]; then
		WaitForUserEnter
		exit 
	else
		SSHConfigured=1
	fi
	
	# Disable Shared LPAR and Cross LPAR collection if HMC Name is unset
	if [[ ${Hmc_Name_PM} == "" && $SSHConfigured -eq 1 ]]
	then
		UnsetPMExt
		SetXlparInterval 
	else
		if [[ $SSHConfigured -eq 0 ]]; 
		then
			echo $(dspmsg pm_ext.cat -s 1 10 'Failed to connect to HMC. Please check if password-less ssh to HMC is setup, and HMC name and HMC user is correct. ')
			WaitForUserEnter
			exit 
		fi
		SetPMExt
	fi
	
	val=`/usr/bin/grep Hmc_Name_PM ${PMCONF}`
	if [[ $? -ne 0 ]]; then
		/usr/bin/cat ${PMCONF} > /tmp/_pmconf
		echo >> /tmp/_pmconf
		echo '# HMC Name and User ID' >> /tmp/_pmconf
		echo "Hmc_Name_PM:" >> /tmp/_pmconf
		echo "Hmc_User_PM:" >> /tmp/_pmconf
		echo >> /tmp/_pmconf
		/usr/bin/cp /tmp/_pmconf ${PMCONF}
	fi

	/usr/bin/sed "s/Hmc_Name_PM:.*/Hmc_Name_PM:${Hmc_Name_PM}/" ${PMCONF} > /tmp/_pmconf
	/usr/bin/cp /tmp/_pmconf ${PMCONF}
	/usr/bin/sed "s/Hmc_User_PM:.*/Hmc_User_PM:${Hmc_User_PM}/" ${PMCONF} > /tmp/_pmconf
	/usr/bin/cp /tmp/_pmconf ${PMCONF}
	
	val=`/usr/bin/grep Hmc_Name_PM ${PMCONF}`
	if [[ $? -eq 0 ]]; then
		echo $(dspmsg pm_ext.cat -s 1 4 'Successfully updated HMC Information ')
	else
		echo $(dspmsg pm_ext.cat -s 1 5 'Failed to update HMC Information ')
		WaitForUserEnter
		exit 
	fi
	/usr/bin/rm -f /tmp/_pmconf 
	
	WaitForUserEnter
}

GetESACustInfo()
{
	
	tmpsize=`df -m /tmp | grep -v Filesystem | awk '{print $3}' 2>/dev/null`
	varsize=`df -m /var | grep -v Filesystem | awk '{print $3}' 2>/dev/null`
	
	## If /tmp has less than 1 MB of free size, return
	if [[ $tmpsize -lt 1 ]]; then
		return
	fi
	
	## If /var has less than 1 MB of free size, return
	if [[ $varsize -lt 1 ]]; then
		return
	fi
	
	## Get the PM configuration file path
	PMCONF=/var/perf/pm/config/pmconf
	
	## Get the email address from PM config file
	PM_Email=`grep "^email_PM:" ${PMCONF} | cut -d':' -f2 | sed -e 's/^[ \t]*//'`
	
	## If PM Email is already updated, return
	if [[ $PM_Email != "" ]]; then
		return
	fi
	
	## Get ESA configuration file path, this is found only if ESA is enabled
	file="/var/esa/data/IBM_ESAconfig.properties"
	
	## If ESA configuration file is not available, return, this file is available only if ESA is enabled
	if [[ ! -e $file ]]; then
		return
	fi
	
	## Array of ESA contact info fields to be captured
	set -A ESA_Fields R_COMPANY_NAME LOCATION_BUILDING LOCATION_ADDRESS1 LOCATION_CITY_OR_LOCALITY LOCATION_STATE_OR_PROVINCE R_COUNTRY_OR_REGION LOCATION_ZIP_OR_POSTAL_CODE R_CONTACT_NAME R_PHONE_NUMBER R_EMAIL_ADDRESS
	
	## Array to get the values of the ESA fields
	set -A ESA_Values
	
	## Loop through all the required fields in ESA and capture the data in array
	n=0
	for i in ${ESA_Fields[@]}
	do
		ESA_Values[$n]=`grep ^$i $file | cut -d'=' -f2 | sed -e 's/^[ 	]*//'`
		n=`expr $n + 1`
	done
	
	## If Building value is blank, move the next address up
	if [[ ${ESA_Values[1]} == "" ]]; then
		ESA_Values[1]=ESA_Values[2]
		ESA_Values[2]=""
	fi
	
	## Array of PM contact info fields
	set -A PM_Fields Company_Name_PM Address_PM Address1_PM City_PM state_PM country_PM countrycode_PM contactperson_PM phone_PM email_PM
	
	## Path for pmconf backup file 
	PMCONF_UPD="/tmp/$$_pmconf_upd"
	
	## Path for pmconf temp file
	PMCONF_TMP="/tmp/$$_pmconf_tmp"
	
	## Path for pmconf backup file for comparison with original pmconf
	PMCONF_BKUP="/tmp/$$_pmconf_bkup"
	
	## Copying original pmconf file which will be used for modifying 
	/usr/bin/cp ${PMCONF} ${PMCONF_UPD}
	
	## If copy of pmconf file is not found, return
	if [[ ! -e ${PMCONF_UPD} ]]; then
		return
	fi
	
	## Copying original pmconf file as backup for comparison later
	/usr/bin/cp ${PMCONF} ${PMCONF_BKUP}
	
	## If backup file is not found, return
	if [[ ! -e ${PMCONF_BKUP} ]]; then
		/usr/bin/rm ${PMCONF_UPD}
		return
	fi
	
	## Loop through all the required fields in PM and update the pmconf backup file
	n=0
	for i in ${PM_Fields[@]}
	do
		/usr/bin/sed "s/${i}:.*/${i}:${ESA_Values[$n]}/" ${PMCONF_UPD} > ${PMCONF_TMP}
		/usr/bin/cp ${PMCONF_TMP} ${PMCONF_UPD}
		n=`expr $n + 1`
	done
	
	
	## If pmconf backup file is available and difference is only in content of lines, 
	##and if line numbers are greater than or equal only then replace the original file with updated backup pmconf file
	if [[ -e ${PMCONF_UPD} ]]; then
		
		diff ${PMCONF_UPD} ${PMCONF} 2>/dev/null >&2
		if [[ $? -ne 0 ]]; then
			## If updated and pmconf file is NOT same, 
			
			## If No modification is made to original pmconf, only then replace with ESA updated pmconf
			diff ${PMCONF_BKUP} ${PMCONF} 2>/dev/null >&2
			if [[ $? -eq 0 ]]; then
				/usr/bin/cp ${PMCONF_UPD} ${PMCONF}
			fi
		fi
		
	fi
	
	## Unset the array used
	unset ESA_Fields
	unset ESA_Values
	unset PM_Fields
	
	## Remove the pmconf backup and temp file
	if [[ -e ${PMCONF_UPD} ]]; then
		/usr/bin/rm ${PMCONF_UPD}
	fi
	
	if [[ -e ${PMCONF_BKUP} ]]; then
		/usr/bin/rm ${PMCONF_BKUP}
	fi
	
	if [[ -e ${PMCONF_TMP} ]]; then
		/usr/bin/rm ${PMCONF_TMP}
	fi
	
	return
	
}

EnableDisablePMRec()
{
	OSLEVEL=`/usr/bin/oslevel | awk -F'.' '{printf $1"."$2}'`
	PMPERFREC_STATUS=1
        if [[ ${OSLEVEL} == "6.1" ]]
	then
		## Check for RBAC authorization
		if [[ -f /usr/ios/cli/ioscli ]]
		then
			# If its vios, check for vios authorization
			/usr/bin/ckauth vios.system.perfmgr.config
			if [[ $? -eq 0 ]] 
			then
				PMPERFREC_STATUS=0
			fi
		fi
	else
	        ## Check for RBAC authorization
		if [[ -f /usr/ios/cli/ioscli ]]
		then
			# If its vios, check for vios authorization
			/usr/bin/ckauth vios.system.perfmgr.config
			if [[ $? -eq 0 ]] 
			then
				PMPERFREC_STATUS=0
			fi
		else
			# If its aix, check for aix authorization
			/usr/bin/ckauth aix.system.perfmgr.config
			if [[ $? -eq 0 ]] 
			then
				PMPERFREC_STATUS=0
			fi
		fi	
	fi

	
	if [[ ${PMPERFREC_STATUS} -ne 0 ]]
	then
		return 1
	fi
	
	while getopts ':P:' flag
	do
		case "$flag" in
		P)	Enable_Pm_Recording=$OPTARG
		;;
		[?])	Usage
			exit 10
		;;
		
		esac
	done
	PMCONF=/var/perf/pm/config/pmconf
	PMRecService="pmperfrec"
	PMREC_ENABLED=1
	if [[ ${Enable_Pm_Recording} == "yes" ]]
	then
		/usr/bin/lssrc -s ${PMRecService} >/dev/null 2>&1
		if [[ $? -ne 0 ]]
		then
			# Add pmperfrec service to the SRC subsystem
			/usr/bin/mkssys -p /var/perf/pm/bin/pmperfrec -s ${PMRecService} -u 0 -Q -S -n 30 -f 9 >/dev/null
			if [[ $? -ne 0 ]]
			then
				echo "Failed to add ${PMRecService} service to SRC subsystem"
				return 1
			else
				echo "${PMRecService} is added to SRC subsystem"
			fi
		fi
		
		# If service is not active, start the service
		/usr/bin/lssrc -s ${PMRecService} | /usr/bin/tr -s ' ' | /usr/bin/grep ${PMRecService} | /usr/bin/grep -v grep | /usr/bin/grep ' active' >/dev/null 2>&1
		if [ $? -ne 0 ]
		then
			# Start the pmperfrec service
			/usr/bin/startsrc -s ${PMRecService} >/dev/null 2>&1
			# Confirm whether the pmperfrec service is started
			/usr/bin/lssrc -s ${PMRecService} | /usr/bin/tr -s ' ' | /usr/bin/grep ${PMRecService} | /usr/bin/grep -v grep | /usr/bin/grep ' active' >/dev/null 2>&1
			if [ $? -eq 0 ]
			then
				# Service is active
				PMREC_ENABLED=0
				echo "Started ${PMRecService} service"
			else
				echo "Failed to start ${PMRecService} service"
			fi
		else
			# Service is already active
			PMREC_ENABLED=0
		fi
		
		# Check if pmperfrec entry listed in inittab, if no, add it
		lsitab pmperfrec >/dev/null 2>&1
		if [[ $? -ne 0 && ${PMREC_ENABLED} -eq 0 ]]
		then
			# Add pmperfrec entry to inittab
			/usr/sbin/mkitab 'pmperfrec:2:once:/var/perf/pm/bin/config_pm_ext.sh -P yes' >/dev/null 2>&1
			# Confirm whether pmperfrec entry is added in inittab
			lsitab pmperfrec >/dev/null 2>&1
			if [[ $? -ne 0 ]]
			then
				echo "Failed to add the entry in /etc/inittab"
			else
				echo "Updated entry in /etc/inittab"
			fi
		fi
	elif [[ ${Enable_Pm_Recording} == "no" ]]
	then
		# To disable PM Perf recording
		/usr/bin/lssrc -s ${PMRecService} >/dev/null 2>&1
		if [[ $? -eq 0 ]]
		then
			# Make sure the service is stopped before removing from SRC Subsystem, else the process will be running
			/usr/bin/lssrc -s ${PMRecService} | /usr/bin/tr -s ' ' | /usr/bin/grep ${PMRecService} | /usr/bin/grep -v grep | /usr/bin/grep ' active' >/dev/null 2>&1
			if [ $? -eq 0 ]
			then
				 # Stop the pmperfrec serivce 
				/usr/bin/stopsrc -s ${PMRecService} >/dev/null 2>&1
				# Confirm whether the pmperfrec service is stopped
				/usr/bin/lssrc -s ${PMRecService} | /usr/bin/tr -s ' ' | /usr/bin/grep ${PMRecService} | /usr/bin/grep -v grep | /usr/bin/grep ' active' >/dev/null 2>&1
				if [ $? -ne 0 ]
				then
					echo "Stopped ${PMRecService} service"
				else
					echo "Failed to stop ${PMRecService} service"
				fi
			fi
		fi
		
		# Check if pmperfrec entry listed in inittab, if yes, remove it
		lsitab pmperfrec >/dev/null 2>&1
		if [[ $? -eq 0 ]]
		then
			# Removing pmperfrec entry from inittab
			/usr/sbin/rmitab pmperfrec >/dev/null 2>&1
			# Confirm whether pmperfrec entry is removed from inittab
			lsitab pmperfrec >/dev/null 2>&1
			if [[ $? -eq 0 ]]
			then
				echo "Failed to remove the entry in /etc/inittab"
			else
				echo "Removed pmperfrec entry in /etc/inittab"
			fi
		fi
	fi
}


main()
{

	#IT should not run inside WPAR
	Is_WPAR=`/usr/bin/uname -W`
	if [[ ${Is_WPAR} -ne 0 ]]
	then
	        echo "PM Service is not supported inside WPAR"
	        exit 1
	fi
	
	## Check for RBAC authorization
	if [[ -f /usr/ios/cli/ioscli ]]
	then
		# If its vios, check for vios authorization
		/usr/bin/ckauth vios.system.perfmgr.config
		rc=$?
		if [[ $rc -ne 0 ]]; then
			exit 1
		fi
	else
		# If its aix, check for aix authorization
		/usr/bin/ckauth aix.system.perfmgr.config
		rc=$?
		if [[ $rc -ne 0 ]]; then
			exit 1
		fi
	fi
	
	ARG1=$1
	if [[ ${ARG1} == "-C" || ${ARG1} == "-c" || ${ARG1} == "-H" ]]
	then
		if [[ ! -f /var/perf/pm/bin/pmcfg_ext ]]
		then 
			echo $(dspmsg pm_ext.cat -s 1 11 'pmcfg extension script is not available' )
			
			exit 1
		fi
	fi
	
	if [[ ${ARG1} == "-C" ]]
	then
		
		HwType=`/usr/sbin/getsystype -i | /usr/bin/awk '{print $2}' 2>/dev/null`
		
		/usr/bin/grep "# PMExt:2" ${PMCONF} > /dev/null 2>&1
		if [[ $? -eq 0 || ${HwType} -gt 7 ]]
		then
			shift
			SetXlparInterval $*
		else
			echo "Error: HMC information has not been entered."
			echo "Please enter HMC information using SMIT.\n"
			echo "====================================
Steps to enter HMC information
====================================
1. From the command line, type 'smit topas'.
2. Select 'Setup Performance Management'.
3. Select 'Change/Show HMC Information' to show/change the HMC information.\n"
			exit 1
		fi
	elif [[ ${ARG1} == "-c" ]]
	then
		shift
		GetXlparInterval
	elif [[ ${ARG1} == "-H" ]]
	then
		shift
		SetHMCInfo $*
	elif [[ ${ARG1} == "-E" ]]
	then
		shift
		## Call to update PMCONF file from ESA
		GetESACustInfo
	elif [[ ${ARG1} == "-P" ]]
	then
		EnableDisablePMRec $*
	fi
}
PMCONF=/var/perf/pm/config/pmconf
main $*

