#!/usr/bin/ksh -p
# *****************************************************************************
#   (C) Copyright 2000-2008 Hewlett-Packard Development Company, L.P.
#   HPVM: $Id: hpvmdevtranslate 8227 2008-11-04 20:45:28Z spider $ - HP CONFIDENTIAL
# *****************************************************************************
#       hpvmdevtranslate - Translate guest legacy backing devices into agile devices
#
#
# Usage:
#	hpvmdevtranslate -a /var/opt/hpvm/common/hpvm_mgmtdb_pre1131
#       hpvmdevtranslate [-v] -a hpvm_mgmtdb"
#       hpvmdevtranslate [-v] -a "
#       hpvmdevtranslate [-v] -P guestname"
#       hpvmdevtranslate [-v] -u "
#       hpvmdevtranslate -v "
#
# This program produces an output script /var/opt/hpvm/common/hpvm_dev_convert  
# Before running this script first review it. If you want to run it then
# Comment out the line indicated that prevent the script from running.
#
PATH=$PATH:/opt/hpvm/bin:/usr/sbin:/usr/ucb:/usr/bin:/sbin:/usr/contrib/bin
hpvminfo=/opt/hpvm/bin/hpvminfo
alias hpvmmodify=/opt/hpvm/bin/hpvmmodify
alias hpvmdevmgmt=/opt/hpvm/bin/hpvmdevmgmt
alias hpvmstatus=/opt/hpvm/bin/hpvmstatus
alias hpvmhostrdev=/opt/hpvm/bin/hpvmhostrdev
alias grep=/usr/bin/grep
alias getlunwwids="/usr/sbin/scsimgr -p get_attr -a wwid -a dev_type -a device_file all_lun"
alias awk=/usr/bin/awk
alias cat=/usr/bin/cat
alias mv=/usr/bin/mv
alias sed=/usr/bin/sed
alias find=/usr/bin/find
alias ls=/usr/bin/ls

hpvm_dev_db=/var/opt/hpvm/common/hpvm_mgmtdb 
hpvmlunmap=/var/opt/hpvm/common/hpvm_lunwwid_map
convert=/var/opt/hpvm/common/hpvm_dev_convert
guestDir=/var/opt/hpvm/guests
headline="HPVM MANAGEMENT_DB START"
endline="HPVM MANAGEMENT_DB EOF"
guestUuid=":"
devtape=":Sequential_Access:"
devctl=":Array_Controller:"
devcd_dvd=":CD/DVD:"
devchgr=":Medium_Changer:"
usageError=false
unDo=false
convertGuest=false
convertAll=false
version=false
dbArg=false
isHost=false
head=false
icUpgrade=false
numOpts=0
#
# Check installed as an HPVM Host
# Only good for HPVM V4 
#
if [[ -x "${hpvminfo}" ]] ; then
    versionStr=$(hpvminfo -v | grep  "Version")
    if print "${versionStr}" | grep -q -e ".04." ; then
        if hpvminfo -M | grep -q ":host:" ; then
            isHost=true
        fi
    fi
fi
if [[ ${isHost} != "true" ]] ; then
    print "hpvmdevtranslate must be run on an HPVM V4 Host"
    usageError=true
fi
#
# Process options
#
while getopts auvP: opt ; do
    case ${opt} in
      (u) # Undo the previous conversion
        unDo=true
        numOpts=$(expr $numOpts + 1)
      ;;
      (a) # Convert all current guests 
        convertAll=true
        numOpts=$(expr $numOpts + 1)
      ;;
      (P) # Convert a single guest using the current hpvm_mgmtdb
        convertGuest=true
        numOpts=$(expr $numOpts + 1)
        if hpvmstatus -P ${OPTARG} >/dev/null 2>&1 ; then
            guestName=${OPTARG}
            guestUuid=$(hpvmstatus -P ${OPTARG} -M | awk '{FS=":";print $2}')
        else 
            usageError=true
            print "${OPTARG} is not a defined guest."
        fi
      ;;
      (v) # Print version of utility
        version=true
        echo "${versionStr}"
        echo "    The primary purpose of this program is to help HPVM"
        echo "    administrators during an HPVM host upgrade from 11iv2 to 11iv3." 
        echo "    This program produces a script, /var/opt/hpvm/common/hpvm_dev_convert" 
        echo "    that can be executed to convert existing guest devices to the new"
        echo "    11iv3 agile devices." 
        echo " "
        echo "    If you have completed a cold install of 11iv3 and have just installed"
        echo "    the new HPVM V4.0 depot then you are ready to bring back your backup"
        echo "    copy of /var/opt/hpvm.  To do this first stop hpvm by running "
        echo "    /sbin/init.d/hpvm stop . You can now restore the /var/opt/hpvm "
        echo "    directory. After restoring the /var/opt/hpvm directory startup hpvm"
        echo "    with /sbin/init.d/hpvm start.  Now you are ready to run this program."
        echo "    by entering:"
        echo "    /opt/hpvm/bin/hpvmdevtranslate -a /var/opt/hpvm/common/hpvm_mgmtdb_pre1131"
        echo " "
        echo "    This same program can be used to reconfigure all guests or a single guest "
        echo "    to use the new 11iv3 agile devices in place of the old legacy devices. "
        echo ""
        echo "    The conversion script, /var/opt/hpvm/common/hpvm_dev_convert, needs"
        echo "    to be reviewed and edited to be runnable." 
        echo "    Take special note of messages marked with ERROR: as they represent"
        echo "    conversions which were not possible."
        echo ""
      ;;
      ([?]) # Ignore anything else
            usageError=true
        :
      ;;
    esac
done
shift OPTIND-1
if [[ ${numOpts} -eq 0 ]] ; then
    if [[ ${version} = "true" ]] ; then
        exit 0
    else
        usageError=true
    fi
fi
if [[ ${numOpts} -gt 1 ]] ; then
    usageError=true
    print "Only -v can be used with other options."
fi
#
# Make sure that no guests are running
#
hpvmstatus -M | awk '{FS=":";print $1" "$11}' | while read gname gstatus 
do
    guestList="${guestList} ${gname}"
    print "${gstatus}" | grep -qi "Off" || 
        {
        print "No guests can be running"
        exit 1 
        }
done
#
# If we have a database arguement use it
# Otherwise reference the existing database
#
if [[ ${#} -eq 1 ]] ; then
    if [[ -f ${1} ]] ; then
        hpvmdbfile=${1}
        db_version=$(grep "# Version " ${hpvmdbfile} 2>/dev/null)
        if [[ -n "${db_version}" ]] ; then
            if grep -q "${db_version}" /var/opt/hpvm/common/hpvm_mgmtdb ; then
	        icUpgrade=true
            fi
        else
            print "${hpvmdbfile} does not conform to an hpvm_mgmtdb format"
            usageError=true
        fi
    else 
        print "${hpvmdbfile} does not conform to an hpvm_mgmtdb format"
        usageError=true
    fi
else
    hpvmdbfile=/var/opt/hpvm/common/hpvm_mgmtdb
fi
#
# Check that the database is valid
#
if [[ ${usageError} != "true" ]] ; then
    if [[ -f ${hpvmdbfile} ]] ; then
        if grep -q "${headline}" ${hpvmdbfile} ; then
            if grep -q "${endline}" ${hpvmdbfile} ; then
                dbArg=true
            else
                print "${hpvmdbfile} does not conform to an hpvm_mgmtdb format"
                usageError=true
            fi
        else 
            print "${hpvmdbfile} does not conform to an hpvm_mgmtdb format"
            usageError=true
        fi
    else
        print "${hpvmdbfile} does not exist as a regular file"
        usageError=true
    fi
fi
if ${usageError} ; then
    echo "Usage: hpvmdevtranslate [-v] -a hpvm_mgmtdb"
    echo "       hpvmdevtranslate [-v] -a "
    echo "       hpvmdevtranslate [-v] -P guestname"
    echo "       hpvmdevtranslate [-v] -u "
    echo "       hpvmdevtranslate -v "
    exit 1 
fi
#
# Save undo files for a -u 
#
if ${unDo} ; then
    found=$(find /var/opt/hpvm/common -name hpvm_mgmtdb.xlateundo -ctime -2)
    if [[ -n "${found}" ]] 
    then
        for guest in ${guestList}
        do
            if [[ -f $guestDir/$guest/vmm_config.xlateundo ]]
            then
                if [[ -f $guestDir/$guest/vmm_config.next ]]
                then 
                    mv $guestDir/$guest/vmm_config.next $guestDir/$guest/vmm_config.current
                fi
                cp  $guestDir/$guest/vmm_config.current $guestDir/$guest/vmm_config.xlatepreundo
                cp  $guestDir/$guest/vmm_config.xlateundo  $guestDir/$guest/vmm_config.current
                rm  $guestDir/$guest/vmm_config.xlateundo
            fi
        done
	cp /var/opt/hpvm/common/hpvm_mgmtdb /var/opt/hpvm/common/hpvm_mgmtdb.xlatepreundo
        cp /var/opt/hpvm/common/hpvm_mgmtdb.xlateundo /var/opt/hpvm/common/hpvm_mgmtdb
	rm /var/opt/hpvm/common/hpvm_mgmtdb.xlateundo
    else
	if [[ -f /var/opt/hpvm/common/hpvm_mgmtdb.xlateundo ]] ; then
	    print "The last hpvmdevtranslate operation was done more than 2 days ago."
	    print "Undoing an old translation will remove any device changes that have"
	    print "happened since that translation. If you still want to undo this old"
	    print "translation execute this command and retry the undo operation:"
	    print " "
	    print "   	#touch /var/opt/hpvm/common/hpvm_mgmtdb.xlateundo"
	else
	    print "No /var/opt/hpvm/common/hpvm_mgmtdb.xlateundo was found indicating"
	    print "that there is no previous hpvmdevtranslate operation that"
	    print "can be undone."
        fi
    fi
    exit 0
fi
#
# If we have a different database we need to reset 
# the reserved devices to be sure that no stale rdevs
# remain set.
#
if [[ ${#} -eq 1 ]] ; then
    for rdev in `hpvmdevmgmt -l rdev | awk '{FS=":";print $1 }' | sed 's@,.*@@'` 
    do
	hpvmdevmgmt -d rdev:$rdev
    done
    rm -f /var/opt/hpvm/common/hpvm_devinit
    hpvmdevmgmt -I
    hpvmhostrdev -u
    if [[ ${icUpgrade} = "true" ]] ; then
        rm -f ${hpvm_dev_db}.nogdevs
        cat ${hpvm_dev_db} | while read -r line
	do
	    if echo $line | grep -q ":CONFIG=gdev," ; then
		if echo $line | grep -q ",DEVTYPE=NIC" ; then
		    echo $line >>${hpvm_dev_db}.nogdevs
                else if echo $line | grep -q ",DEVTYPE=SWITCH" ; then 
		        echo $line >>${hpvm_dev_db}.nogdevs
                     fi
                fi
            else 
		echo $line >>${hpvm_dev_db}.nogdevs
            fi
        done
	if [[ -f ${hpvm_dev_db}.nogdevs ]] ; then
	    mv ${hpvm_dev_db}.nogdevs ${hpvm_dev_db}
        fi
    fi
fi
#
# Get the systems device map
#
if [[ -f ${hpvmlunmap} ]] ; then
    mv ${hpvmlunmap} ${hpvmlunmap}.last
fi
getlunwwids > $hpvmlunmap 
if [[ ! -f ${hpvmlunmap} ]] ; then
    echo "Unable to create ${hpvmlunmap}"
    exit 1
fi
if [[ -f ${convert} ]] ; then
    mv -f ${convert} /var/opt/hpvm/common/hpvm_dev_convert.last
fi
#
# Make sure that the existing hpvm_mgmtdb is current
# with respect to guest configurations. and that no 
for guest in ${guestList}
do
    hpvmmodify -F -P $guest >/dev/null 2>&1
    if [[ -f $guestDir/$guest/vmm_config.next ]]
    then 
        mv $guestDir/$guest/vmm_config.next $guestDir/$guest/vmm_config.current
    fi
    cp  $guestDir/$guest/vmm_config.current $guestDir/$guest/vmm_config.xlateundo
done
# set guestlist to single guest if -P was specified
if [[ -n ${guestName} ]]  ; then
    guestList=${guestName}
fi
cp /var/opt/hpvm/common/hpvm_mgmtdb /var/opt/hpvm/common/hpvm_mgmtdb.xlateundo
print "#####################################################" >${convert}
print "#  This script must be edited to make it runable." >>${convert}
print "#  While reviewing the script take special note" >>${convert}
print "#  of lines that begin ERROR: as" >>${convert}
print "#  these lines are from devices for which there was" >>${convert}
print "#  no conversion to the new 11iv3 devices."  >>${convert}
print "#####################################################" >>${convert}
print "#Comment out the next line to make this script runnable." >>${convert}
print "exit 1  # make this line a comment " >>${convert}
print "# The following devices on the 11iv3 system have no valid wwid" >>${convert}
print "# and therefore prevent mappings from the 11iv2 devices." >>${convert}
print "Creating conversion script"
print "#" >>${convert}
for dev in `cat $hpvmlunmap`
do
    device=$(print "${dev}" | grep "^:")
    if [[ -n "${device}" ]] ; then
	print "${dev}" | awk '{FS=":";print $2" "$3}' | read devtype devname
	print "#  ${devname} of type ${devtype}"  >>${convert}
    fi
done
if [[ -z "${devname}" ]] ; then
    print "# No devices were found that did not have a valid wwid"  >>${convert}
fi
print "#" >>${convert}
print "#" >>${convert}
token=${guestUuid}
cat ${hpvmdbfile} | while read -r dbLine
    do
    if [[ ${head} != "true" ]] ; then
        if print ${dbLine} | grep -q "${headline}" ; then
            head=true
        fi
    else 
        if print ${dbLine} | grep "${token}" | grep -q "CONFIG=gdev" ; then
            print ${dbLine} | awk '{FS=":";print $1" "$4}' | read olddev devwwid
            if print ${devwwid} | grep -q -e "_[123456789]$" -e "_p[123456789]$" ; then
                partnum=$(print ${devwwid} | sed 's/.*_//' | sed 's/p//')
            else  
                partnum=
            fi
            wwid=$(print ${devwwid} |sed 's/-//g' |sed 's/.*.0x/0x/' |sed -e s/_${partnum}$// -e s/_p${partnum}$//)
            newdev=$(grep "$wwid" $hpvmlunmap | sed 's/.*://')
            if [[ -n ${newdev} ]] ; then
                if [[ -n ${partnum} ]] ; then
                    newdev="${newdev}_p${partnum}"
                else if print "${olddev}" | grep -q "/dev/rscsi/" ; then
		    minor=$(ls -al ${newdev} | awk '{print $6}')
		    ptdev=$(ls -al /dev/pt | grep "$minor" | awk '{print $10]')
		    newptdev=$(print "/dev/pt/${ptdev}")
		    fi
                fi
                thedev=$(print ${olddev} | sed 's/,.*//') 
		if [[ "${newdev}" = "${thedev}" ]] ; then
                    olddev=$(print ${olddev} | sed 's/,/@/' | sed 's/.*@//')
                    thedev=$(print ${olddev} | sed 's/,.*//') 
                fi
                if [[ "${newdev}" != "${thedev}" ]] ; then
                    the_entry=$(hpvmdevmgmt -l gdev:$thedev 2>/dev/null)
                    new_entry=$(hpvmdevmgmt -l gdev:$newdev 2>/dev/null)
                    if [[ -z "${new_entry}" ]] ; then
                        new_entry=$(hpvmdevmgmt -l rdev:$newdev 2>/dev/null)
                        if [[ -n  "${newent}" ]] ; then
                            print "# ERROR: New device ${newent} is a reserved device" >>${convert}
                        else
                            if [[ -n "${guestName}" ]] ; then
                                while [[ -n "${thedev}" ]]
                                do # Only changing one guest so must use hpvmmodify
			          if [[ "${thedev}" != "${newptdev}" && "${thedev}" != "${newdev}" ]] ; then
                                    devspec=$(hpvmstatus -P ${guestName} -d | grep ${thedev})
                                    if [[ -n "${devspec}" ]] ; then
					if print "${devspec}" | grep -q "/dev/rscsi/" ; then
                                            newspec=$(print "${devspec}" | sed -e s@${thedev}@${newptdev}@)
                                        else
                                            newspec=$(print "${devspec}" | sed -e s@${thedev}@${newdev}@)
                                        fi
                                        print "/opt/hpvm/bin/hpvmmodify -P ${guestName} -m ${newspec}" >>${convert}
                                        break;
                                    fi
                                  fi
                                  if print ${olddev} | grep -q "," ; then
                                      olddev=$(print ${olddev} | sed 's/,/@/' | sed 's/.*@//')
                                      thedev=$(print ${olddev} | sed 's/,.*//') 
                                  else 
                                      thedev=
                                  fi
                                done
                            else 
				if print "${thedev}" | grep -q "/dev/rscsi/" ; then
				    print "/opt/hpvm/bin/hpvmdevmgmt -n gdev:${thedev}:${newptdev}" >>${convert}
                                else
                                    print "/opt/hpvm/bin/hpvmdevmgmt -n gdev:${thedev}:${newdev}" >>${convert}
                                fi
                            fi
                        fi
                    else # new device already exists so must use hpvmmodify
                        if [[ -n "${guestName}" ]] ; then
                            while [[ -n "${thedev}" ]]
                            do
			      if [[ "${thedev}" != "${newptdev}" && "${thedev}" != "${newdev}" ]] ; then
                                devspec=$(hpvmstatus -P ${guestName} -d | grep ${thedev})
                                if [[ -n "${devspec}" ]] ; then
				    if print "${devspec}" | grep -q "/dev/rscsi/" ; then
                                         newspec=$(print "${devspec}" | sed -e s@${thedev}@${newptdev}@)
                                    else
                                         newspec=$(print "${devspec}" | sed -e s@${thedev}@${newdev}@)
                                    fi
                                    print "/opt/hpvm/bin/hpvmmodify -P ${guestName} -m ${newspec}" >>${convert}
                                    break;
                                fi
                              fi
                              if print ${olddev} | grep -q "," ; then
                                  olddev=$(print ${olddev} | sed 's/,/@/' | sed 's/.*@//')
                                  thedev=$(print ${olddev} | sed 's/,.*//') 
                              else 
                                  thedev=
                              fi
                            done
                        else # converting all guests
                            startdev=${olddev}
                            for guest in $guestList
                            do
                                olddev=${startdev}
                                thedev=$(print ${olddev} | sed 's/,.*//')
                                while [[ -n "${thedev}" ]]
                                do
				  if [[ "${thedev}" != "${newptdev}" && "${thedev}" != "${newdev}" ]] ; then
                                    devspec=$(hpvmstatus -P ${guest} -d | grep ${thedev})
                                    if [[ -n "${devspec}" ]] ; then
				        if print "${devspec}" | grep -q "/dev/rscsi/" ; then
                                            newspec=$(print "${devspec}" | sed -e s@${thedev}@${newptdev}@)
                                        else
                                            newspec=$(print "${devspec}" | sed -e s@${thedev}@${newdev}@)
                                        fi
                                        print "/opt/hpvm/bin/hpvmmodify -P ${guest} -m ${newspec}" >>${convert}
                                        break;
                                    fi
                                  fi
                                  if print ${olddev} | grep -q "," ; then
                                      olddev=$(print ${olddev} | sed 's/,/@/' | sed 's/.*@//')
                                      thedev=$(print ${olddev} | sed 's/,.*//') 
                                  else 
                                      thedev=
                                  fi
                                done
                            done 
                        fi
                    fi 
                fi
            else
                print "# ERROR: No mapping for device ${olddev} with wwid ${wwid}" >>${convert}
            fi
        fi
    fi
    done
print "######## Done processing devices ########" >>${convert}
chmod +x ${convert}
print "Done processing devices. To make the translations"
print "edit and run the script ${convert}" 
