#!/bin/sh

#
# mvcmp
#
# This script is used to make a vps directory hierarchy point
# to a different vps number.
#
# $Log: mvcmp,v $
# Revision 1.10.4.6.2.2  2007/02/20 20:19:01  pvigliet
# CR Q01492872.  Add log path softlinks for BCM
#
# Revision 1.10.4.6.2.1  2006/12/01 19:11:55  pvigliet
# No code change. Commit for Clearcase migration.
#
# Revision 1.10.4.6  2005/09/19 14:45:48  akeenan
#  Changes dest to dst
#
# Revision 1.10.4.5  2005/08/25 17:40:02  akeenan
# Changes for Linux Tux
#
# Revision 1.10.4.4  2004/02/03 15:53:12  jrumplik
# mod stat only for mps
#
# Revision 1.10.4.3  2004/01/06 16:18:53  jrumplik
# mods for patch globl2.2.0.62
#
# Revision 1.10.4.2  2003/04/29 18:59:06  jrumplik
# isolate pmgr and tms.cfg updates to mps component
#
# Revision 1.10.4.1  2003/04/03 15:11:13  jrumplik
# mods for patch globl2.2.0.24
#
# Revision 1.10  2002/03/14 15:43:53  jrumplik
# bin/echo to preserve tabs on unchanged line in tms.cfg
#
# Revision 1.9  2002/02/28 18:45:06  jrumplik
# tabs for every var in BIND line
#
# Revision 1.8  2002/02/25 15:12:36  jrumplik
# use tabs not space for BIND line
#
# Revision 1.7  2002/02/01 19:54:32  jrumplik
# check if lastnum needs to close a range on pmgr update
#
# Revision 1.6  2002/01/30 19:30:05  jrumplik
# comment
#
# Revision 1.5  2002/01/30 16:21:55  jrumplik
# merged in mods for globl2.0.1.17
#
# MOD	Date		Who	What
# 000	28-aug-95	sab	Originate.
# 001	05-sep-95	sab	Add check for root, and make any failed
#				command exit the script.
# 002	06-mar-96	sab	Fixed some code to check for legacy releases 
#				with no p{bin,lib,images} dirs and pathological
#				cases like removing the current release.
# 003	20-feb-96	sab	Fix bug where we use terminate and mv -f
#				which doesn't work.  Also, fix old usage of
#				modify_vstat.sh that used to use crontab.
# 004	22-apr-96	sab	Fix bug where running mvvps on a system where
#				bin is already a link to pbin fails.  Also
#				finally make mods to fix ethers and hosts.
# 005	12-aug-96	sab	Typo fixed in 5.1.0 missed it in 5.2.0.  A
#				test had "images];" instead of "images ];".
# 006	19-nov-96	jar	changed max vps# from 255 to 899
# 007	15-jul-97	jar	added support for components and rel5.3 dir
#				struct. CHANGED NAME FROM mvvps TO mvcmp
# 008	12-aug-97	jar	added vas support
# 009	09-sep-97	jar	added new vos.cfg comments (for upd'd comments)
# 010	30-sep-97	jar	added new vos.cfg paylinx, geotel procesing
#				enable vstat cron update
# 011	13-nov-97       jar     preserve port numbering if a number existed
#				in vos.cfg


#-----------------------------------------------------------------------------

#
# This variable is for iterating through port numbers.
# It starts at 0 and is bumped each time we write out
# a new line in the cfg file.
#
portIncr=0

#
# A generic function which exits with a non-zero status if any unix command
# fails.  Basically, if any unix commandf fails, bail out.
#
terminate () {
	echo
	echo Operation failed, terminating
	exit 1
}

#
# A function which exits if a vps is in the vpshosts file.
# We use this to avoid moving a vps to one which already exists.
#
exitIfDestInVpsHosts () {
	vhman | \
	while read line; do
        	set $line
        	if [ "$1" = "#" -o "$1" = "$" ]; then
                	continue
        	fi
        	if [ "$1" = "$dst" -a "$3" = "$comptp" ]; then
			echo Destination $comptp $dst already exists.
			exit 1
		fi
	done
}

#
# See if vps numbers are even legal numeric values.
#
chkVpsNumbers () {
	if [ "$src" = "" -o "$src" -lt 1 -o "$src" -gt 899 ]; then
		echo source $comptp number $src is out of range
		terminate
	fi
	if [ "$dst" = "" -o "$dst" -lt 1 -o "$dst" -gt 899 ]; then
		echo source $comptp number $dst is out of range
		terminate
	fi
}

#
# This function is used to separate comments from 'real' cfg entries.
# Comments are just echoed as is, cfg lines are 'fixed' to have
# new port numbers based on the new vps number.  Adding to the
# confusion is that some cfg entries are commented out!  Grrrr!
# The first case in the case statement is a list of these special
# comments that need to get fixed to.  Should any new program be
# added to vos.cfg that is commented out by default, PLEASE ADD
# IT TO THIS LIST!
#
fixVosCfg () {
	cd $VPSHOME/$comptp$src/etc || terminate
	cat vos.cfg | while read line; do
		case "$line" in
		"#atte"* | "#vpstn3270"* | "#orm"* | "#cca_mgr"* | \
  "#appc_cm"* | "#plx_mgr"* | "#geotel"* | "#pos_serv"*)
			#
			# Special program 'comment' fix it anyway.
			#
			fixLine
			;;
		"#"*|"")
			#
			# Regular comment, echo as is.
			#
			echo "$line"
			echo "$line" >> vosNew.cfg
			;;
		*)
			#
			# A real .cfg entry, fix it.
			#
			fixLine
			;;
		esac
	done
	echo Replacing vos.cfg...
	/bin/echo "\t/bin/mv -f vosNew.cfg vos.cfg"
	/bin/mv -f vosNew.cfg vos.cfg || terminate
	cd .. || terminate
	echo ""
}

#
# This function takes a line from vos.cfg (no comments, real
# data lines) and recalculates the port number based on the
# new vps number.  It uses the program version of printf to
# recreate the line.
#
fixLine () {
	args=`echo $line | cut -f1-4 -d" "`
	cmd=`echo $line | cut -f5- -d" "`
	set $args
	if [ "$3" != "-" ]; then
		# this was a componenet upgrade, preserve portnum just in
		# case 5.3 is backed out and vps is kept
		port=`expr $dst % 16 + 39`
		port=`expr $port \* 100 + $portIncr`
		portIncr=`expr $portIncr + 1`
	else
		port="-"
	fi
	#NAME          HOST    PORT    PRI     COMMAND LINE
	printf "%-15s %-7s %-7s %-7s %s\n" $1 $2 $port $4 "$cmd"
	printf "%-15s %-7s %-7s %-7s %s\n" $1 $2 $port $4 "$cmd" >> vosNew.cfg
}


#
# A function which actually does the move.
#
moveIt () {
 . /etc/vpsrc.sh
	echo Updating release directory...
	cd $VPSHOME/$comptp$src || terminate
	/bin/echo "\trm rbin bin rlib lib rimages images"
	rm -f rbin bin rlib lib rimages images || terminate
	cd .. || terminate
	/bin/echo "\tmv $VPSHOME/$comptp$src $VPSHOME/$comptp$dst"
	mv $VPSHOME/$comptp$src $VPSHOME/$comptp$dst || terminate

	cd $VPSHOME/$comptp$dst || terminate




	echo Updating vpshosts file...
	/bin/echo "\tvhman -c$src -d -t${comptp}"
	vhman -c$src -d -t${comptp} || vhman_rc
	/bin/echo "\tvhman -c$dst -t${comptp} -h- -a"
	vhman -c$dst -t${comptp} -h- -a || vhman_rc
	if [ "$comptp" = vas ]; then
		/bin/echo "\tvhman -d -c${src} -tvps -h${VPShostn_src}"
		vhman -d -c${src} -tvps -h${VPShostn_src} || vhman_rc
                /bin/echo "\tvhman -a -c${dst} -tvps -h${VPShostn_dst}"
		vhman -a -c${dst} -tvps -h${VPShostn_dst} || vhman_rc
	fi
	echo ""




}

vhman_rc () {
                        echo
                        echo "***************************************************"
                        echo "***************************************************"
                        echo "CORRECT HOSTNAME IN THE ABOVE VHMAN AND RERUN VHMAN"
                        echo "***************************************************"
                        echo "***************************************************"
                        echo
}

tmscfg_update () {
	# update tms.cfg
	if [ -f $VPSHOME/common/etc/tms/tms.cfg ]; then
	echo Updating $VPSHOME/common/etc/tms/tms.cfg
        exec 4<  $VPSHOME/common/etc/tms/tms.cfg
        while true; do
                # Read a line. Break when EOF
                read line <&4 || break
                case $line in
                BIND*) primary=`echo $line | cut -d" " -f 5`
                        secondary=`echo $line | cut  -d" " -f 6`
                        beginning=`echo $line | cut -d" " -f1-4| tr " " "\t"`
                        ending=`echo $line | cut  -d" " -f7- | tr " " "\t"`
                        if [ "$primary" = "$src" ]; then
                                primary="$dst"
                        fi
                        if [ "$secondary" = "$src" ]; then
                                secondary="$dst"
                        fi
                        /bin/echo "$beginning\t$primary\t$secondary\t$ending" >> $VPSHOME/common/etc/tms/tms.cfg-new
                        ;;
                *) /bin/echo "$line" >> $VPSHOME/common/etc/tms/tms.cfg-new
                        ;;
                esac
        done
                mv -f $VPSHOME/common/etc/tms/tms.cfg-new $VPSHOME/common/etc/tms/tms.cfg
	fi	

}


cronstat_upd () {
	echo Updating vstat cron scripts...
	if [ -f $VPSHOME/bin/modify_vstat.sh ]; then
		$VPSHOME/bin/modify_vstat.sh $src $dst
	else
		/opt/vps/PERImps/bin/modify_vstat.sh $src $dst
	fi
	echo ""
}

statslink_upd () {
	if [ -f $VPSHOME/mpsN ]; then
		cd $VPSHOME
	else
		cd /opt/vps
	fi
	echo Updating stats link...
	rm -f mpsN
	ln -s mps${dst} mpsN
	echo ""

	if [ "$SysType" = "Linux" -a "$comptp" = "mps" ]; then
		echo Updating BCM log links...
		rm -f /var/log/info.mps.log
		rm -f /var/log/warning.mps.log
		rm -f /var/log/alarm.mps.log
		ln -s /var/log/info.mps.${dst}.log /var/log/info.mps.log
		ln -s /var/log/warning.mps.${dst}.log /var/log/warning.mps.log
		ln -s /var/log/alarm.mps.${dst}.log /var/log/alarm.mps.log
		echo ""
	fi

}

pmgr_update () {
#check if pmgr.cfg needs update
if [ -f $VPSHOME/common/etc/pmgr.cfg ]; then
	echo "Updating $VPSHOME/common/etc/pmgr.cfg"
	echo " "
	mv -f $VPSHOME/common/etc/pmgr.cfg $VPSHOME/common/etc/pmgr.cfg-save$thisdate
        exec 4<  $VPSHOME/common/etc/pmgr.cfg-save$thisdate || terminate
        while true; do
                # Read a line. Break when EOF
                read line <&4 || break
		case $line in
		cfgrsrc*mps*|cfgrsrc*vps*) compnos=`echo $line | cut -d"." -f 5 | sed 's/\*/asterisk/'`
			beginning=`echo $line | cut -d"." -f1-4`
			if [ "$compnos" = "$src" ]; then
				compnos="$dst"
			else
				# in case it wasn't so clear......
				# check for number in range x-y or in comma seperated list
				compnolist=`echo $compnos | tr -s "," " "`
				expandedlist=""
				for item in $compnolist; do
					case $item in
						*-*)
							range=`echo $item | awk '{ n = split($0,c,"-"); for (i = c[1]; i <= c[2] ; ++i)   printf("%s%s"," ",i) }'`
							expandedlist="$expandedlist $range"
							;;
						*) expandedlist="$expandedlist $item"	
							;;
					esac
				done
				# sort in case it was not in order
				finalexpandedlist=`echo $expandedlist | tr " " "\012" | sort -n -u`
				expandedlist=`echo $finalexpandedlist | tr "\012" " "`
				# if the component number is in the expanded list, change it to its destined
				updatedlist=""
				for n in $expandedlist; do
					if [ "$n" = "$src" ]; then
		                                n="$dst"	
					fi
					updatedlist="$updatedlist $n"
				done
				# sort so the new number fits in correctly
				list=`echo $updatedlist | tr " " "\012" | sort -n -u`
				updatedlist=`echo $list | tr "\012" " "`
				# ok, collapse the list into range or comma seperated list
				oldnum="9999999"
				needdash="no"
				dash="-"
				comma=""
				asterisk="*"
				compnos=""
				for  l in $updatedlist; do
					lastwrote="no"
					n=`expr $oldnum + 1`
					if [ "$n" = "$l" ]; then
						# its consecutive, set the dash flag
						needdash="yes"	
						oldnum="$l"
					else
						# its not a range, check if we need to close a range...
						if [ "$needdash" = "yes" ]; then
							#yes, close it while adding the presently checked num
							compnos="$compnos$dash$oldnum$comma$l"
							#reset for any others in list
							needdash="no"	
							oldnum="$l"
							lastwrote="yes"
						else
							if [ "$l" = "asterisk" ]; then
								compnos="$compnos$comma$asterisk"
								oldnum="9999999"
								lastwrote="yes"
							else
								compnos="$compnos$comma$l"
								oldnum="$l"
								lastwrote="yes"
							fi
						fi
					fi
					if [ "$comma" = "" ]; then
						#ok, done with first pass, use commas now
						comma=","
					fi
				done	
				
			fi
			if [  "$lastwrote" = "no" ]; then
				# straggler waiting to see if it was in a range, just add it
                                if [ "$needdash" = "yes" ]; then
                                        #yes, close the range
                                        compnos="$compnos$dash$oldnum"
                                else
                                        # just this num
                                        compnos="$compnos$comma$oldnum"
                                fi
			fi
				
			echo "$beginning.$compnos" >> $VPSHOME/common/etc/pmgr.cfg || terminate
			;;
		*) echo $line >> $VPSHOME/common/etc/pmgr.cfg || terminate
			;;
		esac

        done
fi
}

#-----------------------------------------------------------------------------

# MAIN
# If we're not root, forget it.
#
SysType=`uname -s`
if [ "$SysType" != "Linux" ]; then
	UserId=`/usr/ucb/whoami`
else
	UserId=`id -un`
fi

if [ "$UserId" != root ]; then
	echo run mvcmp as root
	exit 1
fi

# set date for logs or saved files
thisdate=`date +%m%d%y-%H:%M:%S`

#
# Load our environment (if available and not done already)
#
if [ -f /etc/mpshome ]; then
        MPSHOME=`cat /etc/mpshome`
	VPSHOME="$MPSHOME"
else
        if [ -f /etc/vpshome ]; then
                VPSHOME=`cat /etc/vpshome`
        else
                VPSHOME="/opt/vps"
        fi
        MPSHOME="$VPSHOME"
fi
#

#
# Make sure srp isn't up! 
#
srpup
if [ $? != 0 ]; then
	echo Please take srp down before running mvcmp.
	exit 1
fi

#
# Get any vps numbers that were specified.
#
case $# in
	0)
		src=none
		dst=none
		comptp=none
		;;
	1)
		src=$1
		dst=none
		comptp=none
		;;
	2)
		src=$1
		dst=$2
		comptp=none
		;;
	3)
		src=$1
		dst=$2
		comptp=$3
		;;
	*)
		echo Invalid vps specification.
		echo usage: mvcmp src# dst# component-type
		exit 1
		;;
esac

#
# Get any vps numbers that were not specified.
#
if [ "$src" = none ]; then
	/bin/echo "Please enter source component number: \c"
	read src
fi
if [ "$dst" = none ]; then
	/bin/echo "Please enter destination component number: \c"
	read dst
fi
if [ "$comptp" = none ]; then
		/bin/echo "Please enter component type: \c"
		read comptp
fi


#
# Validate vps numbers.  We check the destination several ways, if it is
# a local file in $VPSHOME, or if there is an entry for it in vpshosts.
#
#chkVpsNumbers
cd $VPSHOME
if [ ! -d $comptp$src ]; then
	echo Source $comptp$src does not exist.
	exit 1
fi
if [ -r $comptp$dst ]; then
	echo Destination $comptp$dst already exists.
	exit 1
fi
exitIfDestInVpsHosts

# check to see that component # is not in use on another node
localHost=`uname -n`
other_cmp=`awk '{ if ($1 == "'$dst'" && ( $2 != "-" && $2 != "'$localHost'" ) && $3 == "'$comptp'" ) { printf("%d%s%s ", $1,":",$2) } }' "$VPSHOME/common/etc/vpshosts"`
if [ "$other_cmp" != "" ]; then
	for compo in $other_cmp; do
		c1=`echo $compo | cut -d: -f1`
		c2=`echo $compo | cut -d: -f2`
		echo "vpshosts shows $comptp$c1 on $c2"
		exit 1
	done
fi

case $comptp in
vas)
# special vas processing
	# check if vps# already exists as a vps
	if [ -d $VPSHOME/vps${dst} ]; then
		echo "vps${dst} already exists on this node."
		echo "If you REALLY want to use vps$dst remotely (with vas${dst}), then"
		echo "remove $VPSHOME/vps$dst, and run vhman to remove the vpshosts entry."
		echo "Then run mvcmp."
		exit 1
	fi
	# get remote vps nodename for before and after pointer to vps.
		/bin/echo "Enter the node name of vps${src} \(VPS node name must be remote!\) : \c"
	                read VPShostn_src
		/bin/echo "Enter the node name of vps${dst} \(VPS node name must be remote!\) : \c"
	        read VPShostn_dst
		;;

mps)
if [ -f $VPSHOME/common/etc/tms/tms.cfg ]; then
	#check if the newnumber is already set in tms.cfg
	exec 4<  $VPSHOME/common/etc/tms/tms.cfg
        while true; do
                # Read a line. Break when EOF
                read line <&4 || break
                case $line in
                BIND*) primary=`echo $line | cut -d" " -f 5`
                        secondary=`echo $line | cut  -d" " -f 6`
                        if [ "$primary" = "$dst" ]; then
                                /bin/echo " $dst already set in the tms.cfg BIND. exiting."
				exit
                        fi
                        if [ "$secondary" = "$dst" ]; then
                                /bin/echo " $dst already set in the tms.cfg BIND. exiting."
				exit
                        fi
                        ;;
                esac
        done
fi
fixVosCfg
pmgr_update
tmscfg_update
moveIt
if [ "$comptp" = "mps" ]; then
cronstat_upd
statslink_upd 
fi
			;;
*) #tmscomm, for one, should only have component dir moved and vpshosts update.
	moveIt
			;;
	
esac

exit 0
