#!/bin/sh
##############################################################################
#  Copyright 2004-2008 Hewlett-Packard Development Company, L.P. 
# Confidential commercial computer software.  Valid license required.
# 
# This is the hpvm guest package script. This script is used to create
# a Serviceguard package from a hpvm Virtual Machine configuration
# This script will scan the virtual machine configuration of the
# passed virtual machine name and then create and distribute a virtual
# machine Serviceguard package.  To assist with cluster administration
# the name of the package as well as the service used to monitor the
# package are the name of the virtual machine.  After running this
# script you should verify and edit each of the files created by this
# script to suite your local requirements In particular the
# identification configuration of the networking parameters must be
# performed manually.  After you have made the appropriate changes on
# each member you can apply the package configuration using the
# cmapplyconf(1) command

# Before running this script:
# 1. The cluster must be created and all member UP and running
# 2. The Virtual Machine must be running in the On state on this Cluster Node
#
# It is strongly recommended that before running this script you have previously:
# 1. Created, deported/imported all of the required storage components to all machines
# 2. That you have successfully run the virtual machine on each node in the cluster.
##############################################################################
# @(#) $Id: hpvm_package.sh 4656 2006-06-14 04:11:33Z tharple $
###############################################################################
# GLOBALS constants and variables

typeset -r CMD=${0##*/}
typeset -r TKBASE=/opt/cmcluster/toolkit/hpvm/
typeset -r SGBASE=/etc/cmcluster/
typeset -r SGCLUSTERCONF=${SGBASE%/}.conf
typeset -r HOSTNAME=`hostname | sed 's/\..*//'`
typeset -r SGVERSION=`/usr/sbin/cmversion 2>/dev/null`

##############################################################################
# Source cluster environment

[[ -s ${CMCLUSTERCONF} ]] && . ${CMCLUSTERCONF}

typeset PACKAGE
typeset PACKAGEDIR

typeset MAINTENACE
typeset MAINTFILE
typeset NODES
typeset SGNODES
typeset SGTHISNODE
typeset SGPKGINFO

typeset HPVMSTATS
typeset HPVMMSE
typeset HUUID
typeset PUUID
typeset ENABLED

typeset CVMDG
typeset VXDG
typeset LVMDG
typeset FILES
typeset SUBNET

typeset RCMD

typeset LEGACY=false
typeset VERBOSE=false
typeset DEBUG=false
typeset QUIET=false
typeset SANITY=false


##############################################################################
# ALIASES

alias Error="print -u2 \\\nERROR : ${CMD} : "

##############################################################################
# FUNCTIONS
function intro
{
    typeset rtn=1
    typeset answer
    cat<<EOF

This is the HP Virtual Machine Serviceguard Toolkit Package Template
Creation script.

This script will assist the user develop and distribute a set of
Serviceguard package configuration template files and associated
start, stop and monitor scripts.

The templates generated by these scripts will handle many guest
configurations, but it is only a template and may not be appropriate
for your particular configuration needs. You are encouraged to review
and modify these template files as needed for your particular
environment.
EOF
    echo "\nDo you wish to continue? (y/n):\c"
    read answer
    if [[ ${answer} = @([Yy]?(es|ES)) ]] ; then
	if /opt/hpvm/bin/hpvmstatus -P ${PACKAGE} 1>/dev/null 2>&1 ; then
	    hpvmstatus -P ${PACKAGE} | \
		awk 'BEGIN{print};/^\[(Virtual Machine|Storage|Network)/{p=1};/^$/{p=0};p==1{print}'
	    echo "\nWould you like to package the Virtual Machine Summarized above? (y/n):\c"
	    read answer
	    if [[ ${answer} = @([Yy]?(es|ES)) ]] ; then
		rtn=0
	    fi
	else
	    Error The selected virtual machine does not exist : ${PACKAGE}
	fi
    fi
    return ${rtn}
}
function usage 
{
    if [[ -n ${*} ]] ; then
	Error ${*}
    fi
    cat  1>&2 <<EOF
Usage: 

/opt/cmcluster/toolkit/hpvm/hpvmsg_package [-VQLs] [-m {0|1}] [-P] vm_name

  -P Virtual machine name 
  -m Maintenance mode 1 - Enabled, 0 - Disabled
  -L Create legacy packages - default modular packages
  -V Verbose
  -Q Quietly performs command taking default actions without additional prompts
  -s Sanity Checks the specific command but does perform the requested action

EOF
    exit 1
}

function get_and_check
{
    typeset rtn=0
    typeset idx=0
    typeset cnt=0
    typeset node
    typeset status
    typeset state
    typeset gnum
    typeset uuid
    typeset start
    typeset answer
    typeset errout

    # Get and check the data we need
    ${QUIET} || echo "\nChecking the virtual machine and cluster configuration"
    if [[ -n ${SGVERSION} ]] && cmviewcl 1>/dev/null 2>&1 ; then
	# The cluster is the basis for node names, ordering and indexes
	cmviewcl -l node | tail +3 |
	while read node status state; do
	    if [[ -z ${NODES[*]} || ${NODES[*]} = @(*[[:space:]]|)${node}@(|[[:space:]]*) ]] ; then
		if [[ ${status} = up && ${state} = running ]] ; then
		    # Optionally limited by node listed on the command line
		    SGNODES[${#SGNODES[*]}]=${node}
		else
		    Error All Serviceguard nodes must be up and running in cluster : ${node}
		    ${QUIET} || cmviewcl -l node 1>&2
		    return 1
		fi
	    fi
	done
	if ! ${QUIET} ; then
	    if SGPKGINFO=`cmviewcl -v -f line -p ${PACKAGE} 2>/dev/null` ; then
		cat <<EOF

The virtual machine ${PACKAGE} is currently a Serviceguard package.
It is recommended that all existing packages be re-packaged each time
the Serviceguard and/or Integrity Virtual Machine product version
changes or when the cluster environment or virtual machine
configuration change. Changes to any of these items may alter the
functionality and behavior of your package.
EOF
		echo "\nWould you like to continue packaging this virtual machine? (y/n):\c"
		read answer
		if [[ ${answer} != @([Yy]?(es|ES)) ]] ; then
		    return 1
		fi
	    fi
	    if [[ -n ${SGPKGINFO} && ${SGPKGINFO} != *module_name* ]] ; then
		LEGACY=true
		cat <<EOF

Analysis of the existing package environment indicates that the virtual
machine has previously been packaged as a legacy package.  Beginning
with Serviceguard 11.18 virtual machine packages can be created as
modular packages.  Modular packages are the preferred type of package
and improvements made to the HPVM toolkit may only be available to
modular packages.  This script can repackage your virtual machine as
either a legacy or modular package.
EOF
		echo "\nWould you like to convert the package to a Modular package? (y/n):\c"
		read answer
		if [[ ${answer} = @([Yy]?(es|ES)) ]] ; then
		    LEGACY=false
		fi
	    fi
	fi
	if /opt/hpvm/bin/hpvmstatus -P ${PACKAGE} 1>/dev/null 2>&1 ; then
	    cnt=0
	    while [[ ${cnt} -lt ${#SGNODES[*]} ]] ; do
		${VERBOSE} && echo Collecting data from ${SGNODES[cnt]} ...
		if HPVMSTATS[cnt]=`node_do ${SGNODES[cnt]} /opt/hpvm/bin/hpvmstatus -P ${PACKAGE} -M` ; then
		    node_do ${SGNODES[cnt]} /opt/hpvm/bin/hpvminfo -S -M | \
			awk -F: '{print $3,$4}' | read HUUID[cnt] PUUID[cnt]
		    if [[ ${SGNODES[cnt]} = ${HOSTNAME} ]] ; then
			# Save this hosts index
			SGTHISNODE=${cnt}
		    fi
		    let cnt+=1
		else
		    Error hpvmstatus failed for virtual machine ${PACKAGE} on node: ${SGNODES[cnt]}
		    return 1
		fi
	    done
	else
	    Error The selected virtual machine does not exist : ${PACKAGE}
	    return 1
	fi
	# The MSE must be correct or correctable or we exit
	if ! mse_do ; then
	    Error The multi-server environment is not configured consistently on each node
	    ${VERBOSE} && echo "Run the following command on each node in the cluster: hpvmstatus -m"  1>&2
	    return 1
	fi
	# Are all of the Group UUIDs the same - Must Fix
	if ! fix_guuids ; then
	    Error The Group UUID for this group of virtual machine hosts are not the same on all Serviceguard nodes
	    return 1
	fi
	cnt=0
	while [[ ${cnt} -lt ${#SGNODES[*]} ]] ; do
	    echo ${HPVMSTATS[cnt]} | awk -F: '{print $2,$3,$11,$12,$26,$46}' |  
	    read uuid[cnt] gnum[cnt] state[cnt] start[cnt] sid[cnt] ENABLED[cnt]
	    let cnt+=1
	done
	cnt=0
        # Verify that any node saying the machine is ON agrees that the sid is this nodes sid
	while [[ ${cnt} -lt ${#SGNODES[*]} ]] ; do
	    if [[ ${state[cnt]} = On && ${sid[cnt]} != ${sid[SGTHISNODE]} ]] ; then
		Error The node on which the virtual machine is running is not consistant across all nodes.
		cat 2>&1 <<EOF
	The hpvmstatus command on each node must indicate the virtual machine is Off
	or is ON with Runsysid value of ${sid[SGTHISNODE]}

	The following is the nodes, state and Runsysid that each instance is reporting:

EOF
		cnt=0
		while [[ ${cnt} -lt ${#SGNODES[*]} ]] ; do
		    echo \\t${SGNODES[cnt]} ${state[cnt]} ${sid[cnt]}
		    let cnt+=1
		done
		return -1
	    fi
	    let cnt+=1
	done
	# Are all of the UUIDs the same?
	if ! fix_uuids ; then
	    Error The UUIDs for this virtual machine are not the same on all Serviceguard nodes
	    return 1
	fi
	# Is the machine running or at least able to be run
	if [[ ${state[SGTHISNODE]} != On ]] && ! errout=`/opt/hpvm/bin/hpvmstart -P ${PACKAGE} -s 2>&1` ; then
	    Error "The virtual machine must either be running or must be able to be run."
	    echo "The hpvmstart -P ${PACKAGE} -s command found the following errors:\n${errout}" 2>&1
	    return 1
	fi
	# Are the VM numbers all the same - Warn only
	if [[ ${gnum[*]} != ${gnum}*( ${gnum}) ]] ; then
	    if ${VERBOSE} ; then
		echo Warning : ${CMD} : VM numbers are different on different nodes
	    fi
	fi
	# No Auto Starting - Must Fix
	if [[ ${start[*]} != Manual*( Manual) ]] ; then
	    cnt=0
	    Error The following nodes do not have there startup behavior set to Manual for this Virtual Machine : ${PACKAGE}
	    while [[ ${cnt} -lt ${#SGNODES[*]} ]] ; do
		if [[ ${start[cnt]} != Manual ]] ; then
		    echo \\t${SGNODES[cnt]}  1>&2
		fi
		let cnt+=1
	    done
	    rtn=1
	fi
    else
	Error Serviceguard must be installed and the cluster up and running before running this command
	rtn=1
    fi
    return ${rtn}
}
function get_backingstore
{
    typeset storage
    typeset network
    typeset dir
    typeset type
    typeset path
    typeset dg
    typeset sub
    typeset dev
    typeset -i rtn=0
    # Get backing store data
    echo ${HPVMSTATS[SGTHISNODE]} | awk -F: '{print $22,$23}' | read storage network
    # Get storage
    echo ${storage} | tr ',' '\012' | awk -F";" '/^disk/{print $8,$9}' |
    while read type path ; do
	if [[ ${type} = file ]] ; then
	    df -n ${path} | tr -s '():' '   ' | read dir path type 
	    if [[ ${FILES[*]} != @(|*[[:space:]])${dir}:${path}:${type}@(|[[:space:]]*) ]] ; then
		FILES[${#FILES[*]}]=${dir}:${path}:${type}
	    fi
	fi
	if [[ ${type} = @(file|lv) ]] ; then
	    if [[ ${path} = /dev/vx/?(r)dsk/* ]] ; then
		echo ${path} | sed 's%/dev/vx/r*dsk/\(.*\)/\(.*\)%\1 \2%' |  read dg lv
		if cfsdgadm display ${dg} 1>/dev/null 2>&1 ; then
		    if [[ ${CVMDG[*]} !=  @(|*[[:space:]])${dg}@(|[[:space:]]*) ]] ; then
			CVMDG[${#CVMDG[*]}]=${dg}
		    fi
		else
		    if [[ ${VXDG[*]} !=  @(|*[[:space:]])${dg}@(|[[:space:]]*) ]] ; then
			VXDG[${#VXDG[*]}]=${dg}
		    fi
		fi
	    elif lvdisplay ${path%/r*}/${path##*/r} 1>/dev/null 2>&1  ; then
		echo ${path} | IFS=/ read dev dev dg lv
		if [[ ${LVMDG[*]} !=  @(|*[[:space:]])${dg}@(|[[:space:]]*) ]] ; then
                    # Is this LVG in the cluster configuration file page 245 
		    LVMDG[${#LVMDG[*]}]=${dg}
		fi
	    else
		# File system on disk device no disk group
		:
	    fi
	fi
    done
    # Get network
    echo ${network} | tr ',' '\012' | awk -F";" '{print $3}' | sort -u | 
    while read vswitch ; do
	hpvmnet -S ${vswitch} -M | awk -F: '{print $8}' | read ip
	netstat -in |  awk '$4==ip{print $3}' ip=${ip} | read sub
	if [[ ${SUBNET[*]} != @(|*[[:space:]])${sub}@(|[[:space:]]*) ]] ; then
	    SUBNET[${#SUBNET[*]}]=${sub}
	fi
    done
    return ${rtn}
}

function package_configure
{
    typeset rtn=0
    typeset modules

    if [[ ! -d ${PACKAGEDIR} ]] ; then
	mkdir -p ${PACKAGEDIR}
	chmod go-w ${PACKAGEDIR}
    fi
    if ${LEGACY} ; then
	${QUIET} || echo "\nCreating legacy style package template files for virtual machine : ${PACKAGE}"
	# Create the Package configuration file
	file_backup ${PACKAGEDIR}${PACKAGE}.config &&
	/usr/sbin/cmmakepkg -p |
	sed "s/^PACKAGE_NAME */& ${PACKAGE}/g
        /# Example : NODE_NAME  \*/a\\
`get_nodes -c`

        /^NODE_NAME[[:space:]]*/d
        s%^RUN_SCRIPT[[:space:]][[:space:]]*%& ${SGBASE}${PACKAGE}/${PACKAGE}.sh%
        s%^HALT_SCRIPT[[:space:]][[:space:]]*%& ${SGBASE}${PACKAGE}/${PACKAGE}.sh%
        /#SERVICE_HALT_TIMEOUT *\(<number of seconds>\)*/a\\
\\
SERVICE_NAME                  ${PACKAGE}\\
SERVICE_FAIL_FAST_ENABLED      NO\\
SERVICE_HALT_TIMEOUT           300\\

        /#MONITORED_SUBNET[[:space:]]*/a\\
`get_subnet -c` 
" | tr -d '\015' >  ${PACKAGEDIR}${PACKAGE}.config &&
	
	# Create the package control script
	file_backup ${PACKAGEDIR}${PACKAGE}.sh &&
	EDITWARN="Warning: A change was made to the function check_and_mount in the file
${PACKAGEDIR}${PACKAGE}.sh.  Checks done by this program indicate that
the edit may have not been made as expected. If the package does not
function properly please review this file and compare it to the output
of the command: /usr/sbin/cmmakepkg -s." &&
	/usr/sbin/cmmakepkg -s | \
	    # The following code adds support for filesystem on disks and partitions to the package control script
	{ awk '/^function +/{if(start&&!end){end=NR};if($2=="check_and_mount"){start=NR}}
                       start&&/^ +RLV.*) *$/{fix=$0;sub(/^[[:space:]]+/,"",fix)}
                       start&&fix&&/^ +;; *$/{semi=$0}
                       start&&fix&&/^ +\*\) *$/{fixrn=NR
                         printf("%s%s%s\n",substr($0,1,length($0)-1),"/dev/dsk/*)",
                           " # Added by hpvmsg_package for filesystems on devices")
                         printf("%s%s\n",substr(semi,1,match(semi,/[^ ]/)-1),fix)
                         printf("%s\n",semi)
                         done=1
                         fix=""}
                       {print $0}
                       END{if (!done||!fixrn||fixrn<start||fixrn>end){exit 1}}' || print -u2 "${EDITWARN}" ; } | 
	sed "/#SERVICE_RESTART\[0\]=\"\"/a\\
\\
SERVICE_NAME[0]=\"${PACKAGE}\"\\
SERVICE_CMD[0]=\"/etc/cmcluster/${PACKAGE}/hpvmsg_ctrl monitor ${PACKAGE}\"\\
SERVICE_RESTART[0]=\"\"

        /# ADD customer defined run commands./a\\
        /etc/cmcluster/${PACKAGE}/hpvmsg_ctrl start ${PACKAGE}\

        /# ADD customer defined halt commands./a\\
        /etc/cmcluster/${PACKAGE}/hpvmsg_ctrl stop ${PACKAGE}\

        /#VG\[0\]=""/a\\
`get_lvm -s`

        /#CVM_DG\[0\]=""/a\\
`get_cvm -s`

       /#VXVM_DG\[0\]=""/a\\
`get_vxvm -s`

       /#FS_TYPE\[0\]=""/a\\
`get_fs -s`

" >  ${PACKAGEDIR}${PACKAGE}.sh &&
	chmod 755 ${PACKAGEDIR}${PACKAGE}.sh &&
	for file in hpvmsg_ctrl hpvmsg_mon hpvmsg_start hpvmsg_stop ; do
	    if cmp -s ${TKBASE}${file} ${PACKAGEDIR}${file} ; then
		:
	    else
		file_backup ${PACKAGEDIR}${file} &&
		sed "s/GUEST/${PACKAGE}/g" ${TKBASE}${file} >  ${PACKAGEDIR}${file} &&
		chmod 755 ${PACKAGEDIR}${file}
	    fi
	done &&
	file_backup -m ${PACKAGEDIR}${PACKAGE}.conf ${PACKAGEDIR}hpvmsg_ext ||
	rtn=-1
    else
	${QUIET} || echo "\nCreating modular style package template files for virtual machine : ${PACKAGE}"
	file_backup ${PACKAGEDIR}${PACKAGE}.conf
	if [[ -n ${CVMDG[*]}${LVMDG[*]}${VXDG[*]} ]] ; then
	    modules="${modules} -m sg/volume_group"
	fi
	if [[ -n ${FILES[*]} ]] ; then
	    modules="${modules} -m sg/filesystem"
	fi
	if [[ -n ${SUBNET[*]} ]] ; then
	    modules="${modules} -m sg/monitor_subnet"
	fi
	cmmakepkg -m sg/failover -m sg/external -m sg/service ${modules} |
	sed "s/package_name */& ${PACKAGE}/
`get_nodes -m`

/^#monitored_subnet[[:space:]]*$/a\\
`get_subnet -m`

/^#external_script[[:space:]]*$/a\\
external_script /etc/cmcluster/${PACKAGE}/hpvmsg_ext

s/^#service_name[[:space:]]*$/service_name ${PACKAGE}/
s%^#service_cmd[[:space:]]*$%service_cmd ${PACKAGEDIR}hpvmsg_mon ${PACKAGE}%
s/^#service_halt_timeout[[:space:]]*$/service_halt_timeout 300/

/#vg[[:space:]]*$/a\\
`get_lvm -m`

/#cvm_dg[[:space:]]*$/a\\
`get_cvm -m`

/#xvvm_dg[[:space:]]*$/a\\
`get_vxvm -m`

/#fs_fsck_opt[[:space:]]*$/a\\
`get_fs -m`

" >  ${PACKAGEDIR}${PACKAGE}.conf &&
	for file in hpvmsg_mon hpvmsg_ext ; do
	    if cmp -s ${TKBASE}${file} ${PACKAGEDIR}${file} ; then
		:
	    else
		file_backup ${PACKAGEDIR}${file} &&
		sed "s/GUEST/${PACKAGE}/g" ${TKBASE}${file} >  ${PACKAGEDIR}${file} &&
		chmod 755 ${PACKAGEDIR}${file}
	    fi
	done &&
	file_backup -m ${PACKAGEDIR}${PACKAGE}.{sh,config} ${PACKAGEDIR}hpvmsg_{ctrl,start,stop} ||
	rtn=1
    fi &&
    ${VERBOSE} && echo "\nThe failover package template files for the Virtual Machine were successfully created."
    return ${rtn}
}

function fix_uuids
{
    typeset cnt=0
    typeset rtn=1
    typeset fix=false
    typeset name
    typeset uuid
    typeset state
    typeset theuuid
    typeset answer
    while true; do
	cnt=0
	while [[ ${cnt} -lt ${#SGNODES[*]} ]] ; do
	    echo ${HPVMSTATS[cnt]} | awk -F: '{print $1,$2,$11}' |  
	    read name[cnt] uuid[cnt] state[cnt]
	    if [[ ${cnt} -eq ${SGTHISNODE} ]] ; then
		theuuid=${uuid[cnt]}
	    fi
	    let cnt+=1
	done
	if [[ ${uuid[*]} = ${uuid}*( ${uuid}) ]] ; then
	    rtn=0
	    break
	else
	    if ${SANITY} || ${fix} ; then
		break
	    else
		if ! ${QUIET} ; then
		    while true ; do
			cnt=0
			cat <<EOF

UUIDs are identifiers used to uniquely identify virtual machine in a
distributed environment. The UUIDs for ${PACKAGE} are not the
same on all nodes in the cluster. To resolve this issue you may
select the UUID you want associated with this virtual machine on all
cluster nodes. After you make your selection this script will modify
the virtual machine on each node where the UUIDs differs.

EOF
			cnt=0
			while [[ ${cnt} -lt ${#SGNODES[*]} ]] ; do
			    printf "%2d) %-20s %s\n" $((cnt+1)) "${SGNODES[cnt]} (${state[cnt]})" ${uuid[cnt]}
			    let cnt+=1
			done
			printf "%2s) %-20s %s\n" Q Quit
			echo "\nEnter the number of the UUID you want:\c"
			read answer
			if [[ ${answer} = [Qq]* ]] ; then
			    rtn=1
			    break 2
			fi
			if [[ ${answer} = +([1-9]) && ${answer} -le ${#SGNODES[*]} ]] ; then
			    let cnt=answer-1
			    if [[ ${state[cnt]} = On || ${state[*]} = Off*( Off) ]] ; then
				echo "\nYou have selected: ${uuid[cnt]}\n"
				echo "The Virtual machine ${PACKAGE} will have its UUID set to this value on all nodes"
				echo "Hit return to confirm your selection:\c"
				read answer
				if [[ -z ${answer} ]] ; then
				    theuuid=${uuid[cnt]}
				    break
				fi
			    else
				cat <<EOF
The UUID you have selected is on a node where the virtual machine is Off
and the virtual machine is running on a different node. The UUID can only be
changed on a virtual machine which is Off. You can correct this issue or
selected a different UUID.
EOF
				echo "Would you like to select a different UUID? (y/n):\c"
				read answer
				if [[ ${answer} != @([Yy]?(es|ES)) ]] ; then
				    break 2
				fi
			    fi
			fi
		    done
		fi
		cnt=0
		while [[ ${cnt} -lt ${#SGNODES[*]} ]] ; do
		    uuid=`echo ${HPVMSTATS[cnt]} | awk -F: '{print $2}'`
		    if [[ ${uuid} != ${theuuid} ]] ; then
			fix=true
                        node_do ${SGNODES[cnt]} /opt/hpvm/bin/hpvmmodify -P ${PACKAGE} -x modify_status=enabled > /dev/null 2>&1 &&
			if ! node_do ${SGNODES[cnt]} /opt/hpvm/bin/hpvmmodify -P ${PACKAGE} -x guest_uuid=${theuuid} ; then
			    Error Cannot correct uuid mis-match between this node and node : ${SGNODES[cnt]}
			    rtn=1
			    break
			else
			    # update the changed status from the node
			    HPVMSTATS[cnt]=`node_do ${SGNODES[cnt]} /opt/hpvm/bin/hpvmstatus -P ${PACKAGE} -M`
			fi
		    fi
		    let cnt+=1
		done
	    fi
	fi
    done
    return ${rtn}
}
function fix_guuids
{
    typeset cnt=0
    typeset rtn=1
    typeset fix=false
    typeset name
    typeset uuid
    typeset state
    typeset theuuid
    typeset answer
    while true; do
	cnt=0
	while [[ ${cnt} -lt ${#SGNODES[*]} ]] ; do
	    node_do ${SGNODES[cnt]} /opt/hpvm/bin/hpvmdevmgmt -l env | \
		sed -n 's/^HPVM_MSE_GROUP_ENTRY:.*UUID=\([^,]*\),GROUPNAME=\([^:]*\):.*/\1 \2/p' | \
		read uuid[cnt] name[cnt]
	    if [[ ${cnt} -eq ${SGTHISNODE} ]] ; then
		theuuid=${uuid[cnt]}
	    fi
	    let cnt+=1
	done
	if [[ ${#uuid[*]} = ${#SGNODES[*]} && ${uuid[*]} = ${uuid}*( ${uuid}) ]] ; then
	    rtn=0
	    break
	else
	    if ${SANITY} || ${fix} ; then
		break
	    else
		if ! ${QUIET} ; then
		    while true ; do
			cnt=0
			cat <<EOF

UUIDs are identifiers used to uniquely identify groups of virtual
machine hosts in a distributed environment. The UUIDs for group
${name} are not the same on all nodes in the cluster.  

To resolve this issue you may select the UUID you want associated with
this group of virtual machine hosts on all cluster nodes. After you
make your selection this script will modify the virtual machine
environment on each node where the UUIDs differs. 

Under most circumstances the selection of any particular will make no
difference in the functionality of the cluster.  If you have licenced
any software using one of the Group UUIDs, an unlikely event, then
select that UUID as your Group UUID.

EOF
			cnt=0
			while [[ ${cnt} -lt ${#SGNODES[*]} ]] ; do
			    printf "%2d) %-20s %s\n" $((cnt+1)) ${SGNODES[cnt]} ${uuid[cnt]}
			    let cnt+=1
			done
			printf "%2s) %-20s %s\n" Q Quit
			echo "\nEnter the number of the UUID you want:\c"
			read answer
			if [[ ${answer} = [Qq]* ]] ; then
			    rtn=1
			    break 2
			fi
			if [[ ${answer} = +([1-9]) && ${answer} -le ${#SGNODES[*]} ]] ; then
			    let cnt=answer-1
			    echo "\nYou have selected: ${uuid[cnt]}\n"
			    echo "The HPVM environment will have its UUID set to this value on all nodes"
			    echo "Hit return to confirm your selection:\c"
			    read answer
			    if [[ -z ${answer} ]] ; then
				theuuid=${uuid[cnt]}
				break
			    fi
			fi
		    done
		fi
		cnt=0
		while [[ ${cnt} -lt ${#SGNODES[*]} ]] ; do
		    if [[ ${uuid[cnt]} != ${theuuid} ]] ; then
			fix=true
			if ! node_do ${SGNODES[cnt]} /opt/hpvm/bin/hpvmdevmgmt -m env:HPVM_MSE_GROUP_ENTRY:attr:UUID=${theuuid} ; then
			    Error Cannot correct uuid mis-match between this node and node : ${SGNODES[cnt]}
			    rtn=1
			    break
			fi
		    fi
		    let cnt+=1
		done
	    fi
	fi
    done
    return ${rtn}
}

function get_nodes
{
   typeset i=0
    typeset node
    for node in ${SGNODES[*]} ; do
	case ${1} in
	    (-c) 
	    echo "NODE_NAME ${node}\\"
	    ;;
	    (-m)
	    if [[ -n ${NODES} ]] ; then
		[[ ${i} -eq 0 ]] && echo " /node_name *\* */d"
		echo "node_name ${node}\\"
	    fi
	    ;;
	esac
	let i+=1
    done
}

function get_lvm
{
    typeset i=0
    typeset dg
    for dg in ${LVMDG[*]} ; do
	case ${1} in
	    (-s) 
	    echo "VG[${i}]=/dev/${dg}\\"
	    ;;
	    (-m)
	    echo "vg ${dg}\\"
	    ;;
	esac
	let i+=1
    done
}

function get_cvm
{
    typeset i=0
    typeset dg
    for dg in ${CVMDG[*]} ; do
	case ${1} in
	    (-s) 
	    echo "CVM_DG[${i}]=${dg}\\"
	    ;;
	    (-m)
	    echo "cvm_dg ${dg}\\"
	    ;;
	esac
	let i+=1
    done
}

function get_vxvm
{
    typeset i=0
    typeset dg
    for dg in ${VXDG[*]} ; do
	case ${1} in
	    (-s) 
	    echo "VXVM_DG[${i}]=${dg}\\"
	    ;;
	    (-m)
	    echo "vxvm_dg ${dg}\\"
	    ;;
	esac
	let i+=1
    done
}

function get_fs
{
    typeset i=0
    typeset fs
    typeset dir
    typeset path
    typeset type
    for fs in ${FILES[*]} ; do
	echo ${fs} | IFS=: read dir path type
	case ${1} in
	    (-s) 
	    echo "LV[${i}]=\"${path}\"; FS[${i}]=\"${dir}\"; FS_TYPE[${i}]=\"${type}\";FS_MOUNT_OPT[${i}]=\"\";FS_UMOUNT_OPT[${i}]=\"\";FS_FSCK_OPT[${i}]=\"\"\\"
	    ;;
	    (-m)
	    cat <<EOF
 fs_name           ${path}\\
 fs_directory     ${dir}\\
 fs_type          \"${type}\"\\
 fs_mount_opt     \"\"\\
 fs_umount_opt    \"\"\\
 fs_fsck_opt      \"\"\\
EOF
	    ;;
	esac
	let i+=1
    done
}

function get_subnet
{
    typeset ip
    typeset i=0
    for ip in ${SUBNET[*]} ; do
	case ${1} in
	    (-c) echo "MONITORED_SUBNET ${ip}\\"
	    ;;
	    (-m) echo "monitored_subnet ${ip}\\"
	    ;;
	esac
	let i+=1
    done
}


function file_backup
{
    typeset dir
    typeset file
    typeset rfiles
    typeset cmd=cp
    typeset opt
    typeset date=`date +%y%h%d.%T`
    while getopts mr: opt ; do
	case ${opt} in
	    (m) # move file 
	    cmd=mv
	    ;;
	    (r) # remote
	    node=${OPTARG}
	    ;;
	esac
    done
    shift OPTIND-1
    if [[ -n ${node} ]] ; then
	# remote backup
	if rfiles=`node_do ${node} ls -pa ${PACKAGEDIR} 2>/dev/null` ; then
	    if [[ -n ${rfiles} && ${rfiles} != @(|*[[:space:]]).backup/@(|[[:space:]]*) ]] ; then
		node_do ${node} mkdir -p ${PACKAGEDIR}.backup
	    fi
	    for file in {hpvmsg_{ext,mon,start,stop},${PACKAGE}.{sh,conf,config}} ; do
		if [[ ${rfiles} = @(|*[[:space:]])${file}@(|[[:space:]]*) ]] ; then
		    node_do ${node} ${cmd} ${PACKAGEDIR}${file} ${PACKAGEDIR}.backup/${file}.${date}
		fi
	    done
	else
	    node_do ${node} mkdir -p ${PACKAGEDIR}
	    node_do ${node} chmod go-w ${PACKAGEDIR}
	fi
    else
	# local backup
	while [[ ${#} -gt 0 && -e ${1} ]]  ; do
	    dir=${1%/*}
	    file=${1##*/}
	    backupDir=${dir}/.backup
	    (
		cd ${dir}
		if [[ ! -d ${backupDir} ]] ; then
		    mkdir  ${backupDir}
		fi
		${cmd} ${1}  ${backupDir}/${file}.${date}
		)
	    shift
	done
    fi
}

function node_do
{
    typeset rtn=1
    typeset node=${1}
    typeset line
    typeset nline=fIrSt
    typeset answer
    shift
    if [[ ${node} = -c ]] ; then
	# remote copy command
	if [[ ${RCMD} = ssh ]] ; then
	    scp ${*} && rtn=0
	else
	    rcp ${*} && rtn=0
	fi
    else
    # Is this a local node (hostname) do
	if [[ `hostname | sed 's/\..*//'` = ${node} ]] ; then
	    ${*}
	    echo ${?} 
	else
        # Do we have a remote method set
	    if [[ -z ${RCMD} ]] ; then
		if ssh ${node} -q -o batchmode=yes -o PasswordAuthentication=no true ; then
		    RCMD=ssh
		elif remsh ${node} true  2>/dev/null ; then
		    RCMD=remsh
		else
		    echo "\nThe hpvmsg_package command cannot ssh or remsh in batch mode to node: ${node}" 1>&2
		    exit 4
		fi
	    fi
	    if [[ ${RCMD} = ssh ]] ; then
		ssh ${node} -q -o batchmode=yes -o PasswordAuthentication=no "${*} ; echo \${?}"
	    else
		remsh ${node} "${*} ; echo \${?}"
	    fi
	fi | 
	while read line ; do
	    if [[ ${nline} != fIrSt ]] ; then
		echo ${nline}
	    fi
	    nline=${line}
	done
	rtn=${nline}
    fi
    return ${rtn}
}

function remote_configure
{
    typeset rtn=1
    typeset ok=true
    typeset errout
    typeset files
    typeset cnt
    if ${ok} ; then
	if ! ${QUIET} ; then
	    echo "\nWould you like to copy the package template files to each cluster member? (y/n):\c"
	    read answer
	fi
	if ${QUIET} || [[ ${answer} = @([Yy]?(es|ES)) ]] ; then
	    for node in ${SGNODES[*]} ; do
		if [[ ${node} != ${SGNODES[SGTHISNODE]} ]] ; then
		    file_backup -m -r ${node}
		    if ${LEGACY} ; then
			files=${PACKAGEDIR}{hpvmsg_{mon,start,stop},${PACKAGE}.{sh,config}}
		    else
			files=${PACKAGEDIR}{hpvmsg_{ext,mon},${PACKAGE}.conf}
		    fi
		    if errout=`node_do -c ${files} ${node}:${PACKAGEDIR} 2>&1` ; then
			:
		    else
			Error "The following errors were detected when attempting to copy the files"
			echo ${errout} 1>&2
			ok=false
			break
		    fi
		fi
	    done
	    ${ok} && ${VERBOSE} && echo "\nThe package template files successfully copied to each cluster member"
	else
	    ok=false
	fi
    fi
    if ${ok} ; then
	if [[ -e ${MAINTFILE} ]] ; then
		cat <<EOF 

This virtual machine was previously packaged and is now in maintenance
mode. To turn off maintenance mode and configure the virtual machine as
a distributed guest use the following command:

# ${0} -P ${PACKAGE} -m 0
EOF
	else
	    if ! ${QUIET} ; then
		echo "\nWould you like to configure this virtual machine as a distributed guest? (y/n):\c"
		read answer
	    fi
	    if ${QUIET} || [[ ${answer} = @([Yy]?(es|ES)) ]] ; then
		cnt=0
		while [[ ${cnt} -lt ${#SGNODES[*]} ]] ; do
		    node=${SGNODES[cnt]}
		    if [[ ${ENABLED[cnt]} = enabled ]] || 
			    node_do ${node} /opt/hpvm/bin/hpvmmodify -P ${PACKAGE} -F -x register_status=enabled >/dev/null 2>&1 && 
			    node_do ${node} /opt/hpvm/bin/hpvmmodify -P ${PACKAGE} -F -i SG_${PACKAGE} >/dev/null 2>&1 &&
			    node_do ${node} /opt/hpvm/bin/hpvmmodify -P ${PACKAGE} -F -j 1  >/dev/null 2>&1 ; then
			:
		    else
			Error Unable to set the application controller or distributed flag for virtual machine : ${PACKAGE}
			ok=false
			break 2
		    fi
		    let cnt+=1
		done
	    else
		ok=false
	    fi
	fi
    fi
    if ${ok} ; then
	echo "\nThe virtual machine has been successfully configured as a Serviceguard package."
	rtn=0
    fi
    return ${rtn}
}

function mse_do
{
    typeset fix=false
    typeset tcnt=0
    typeset dcnt=0
    typeset idx=0
    typeset id=1
    typeset rtn=0
    typeset tnode
    typeset dnode
    typeset mse
    typeset data
    typeset junk
    typeset answer
    typeset sid
    while true ; do
	# Now check that the MSE is setup correctly
	dcnt=0
	unset mse
	while [[ ${dcnt} -lt ${#SGNODES[*]} ]] ; do
	    node_do ${SGNODES[dcnt]} /opt/hpvm/bin/hpvmdevmgmt -l server | sort |
	    while IFS=: read server data junk ; do
		data=`echo $data | tr ',' '\12' | grep -e ^SERVER -e UUID= | sort | tr '\12' ':'`
		mse[dcnt]=${mse[dcnt]:+${mse[dcnt]}+}${server}:${data}
	    done
	    let dcnt+=1
	done
	# The checks are: 
	# 1. All nodes are configured
	# 2. They are all configured the same
	# 3. Each node entry includes all name/value pairs:  PHYSUUID SERVERADDR SERVERID UUID
	if [[ ${#mse[*]} -eq ${#SGNODES[*]} && `print ${mse[*]} | tr ' ' '\12' | sort -u | wc -l` -eq 1 ]] ; then
	    print ${mse[*]} | tr '+ ' '\12\12' | sort -u | 
	    while read data ; do 
		if [[ ${data} != *PHYSUUID=+([0-9a-f-])*(_P@([0-9]|1[0-5])):SERVERADDR=+([0-9.]):SERVERID=[1-9]*([0-9]):UUID=+([0-9a-f-])*(_P@([0-9]|1[0-5])):* ]] ; then
		    rtn=1
		fi
	    done
	else
	    rtn=1
	fi
	if [[ ${rtn} != 0 ]] && ! ${fix} ; then
	    if ! ${QUIET} ; then
		cat <<EOF

Analysis of the hpvmstatus -m command on each node indicates that the
HPVM multi-server environment is not configured correctly.  Before
${CMD} can assist in creating the package configuration template files
the HPVM multi-server environment must be configured.
EOF
		${SANITY} && break
		echo "\nWould you like to configure Serviceguard nodes into the HPVM multi-server environment now? (y/n):\c"
		read answer
	    fi
	    if ${QUIET} || [[ ${answer} = @([Yy]?(es|ES)) ]] ; then
		rtn=0
		id=1
		dcnt=0
		while [[ ${dcnt} -lt ${#SGNODES[*]} ]] ; do
		    dnode=${SGNODES[dcnt]}
		    tcnt=0
		    while [[ ${tcnt} -lt ${#SGNODES[*]} ]] ; do
			tnode=${SGNODES[tcnt]}
			ip=`host ${tnode} | sed 's/.* //'`
			if [[ ${mse[dcnt]} != @(|*+)${tnode}:* ]] ; then
			    if ! node_do ${dnode} /opt/hpvm/bin/hpvmdevmgmt -a server:${tnode} ; then
				rtn=1
				break 2
			    fi
			fi &&
			# get the server ids for the target node
			set -A data `print ${mse[*]} | tr ' +' '\12\12' | sed -n "s/\(${tnode}\):.*:SERVERID=\([0-9]*\):.*/\1:\2/p"`
			if [[ ${data[*]} = ${data}*( ${data}) ]] ; then
			    # The server ids are all the same or unset
			    if [[ -n ${data} ]] ; then
				# find an id which is not in use
				id=1
				while [[ ${mse[*]} = *:SERVERID=* && ${mse[*]} = *:SERVERID=${id}:* ]] ; do
				    let id+=1
				done
			    fi
			    # Save the id for tnode for the next dnode pass
			    if [[ -z ${sid[tcnt]} ]] ; then
				sid[tcnt]=${id}
				let id+=1
			    fi
			    if [[ -z ${data} ]] ; then
				data=${sid[tcnt]}
			    fi
			else
			    # The server id are different on different hosts
			    if [[ ${mse[tcnt]} = *@(|*+)${tnode}:*([!+])SERVERID=[1-9]*([0-9]):* ]] ; then
				# But if I can find the server id on the tnode for the tnode I can assume it is correct
				data=`print ${mse[tcnt]} | tr ' +' '\12\12' | sed -n "s/\(${tnode}\):.*:SERVERID=\([0-9]*\):.*/\1:\2/p"`
			    else
				Error The Server_id for node ${dnode} is cannot be resolved. \
				    \\nSee the HPVM Installation and Administration Manual for assistance in resolving this MSE issue.
				
				rtn=1
				break 2
			    fi
			fi
			if [[ ${mse[dcnt]} = @(|*+)${tnode}:*SERVERID=${data#*:}:* ]] ||
			    node_do ${dnode} /opt/hpvm/bin/hpvmdevmgmt -m server:${tnode}:attr:SERVERID=${data#*:} ; then
			    : 
			fi
			if  [[ ${mse[dcnt]} = @(|*+)${tnode}:*SERVERADDR=${ip}:* ]] ||
			    node_do ${dnode} /opt/hpvm/bin/hpvmdevmgmt -m server:${tnode}:attr:SERVERADDR=${ip} &&
			    [[ ${mse[dcnt]} = @(|*+)${tnode}:*UUID=${HUUID[tcnt]}:* ]] || 
			    node_do ${dnode} /opt/hpvm/bin/hpvmdevmgmt -m server:${tnode}:attr:UUID=${HUUID[tcnt]} &&
			    [[ ${mse[dcnt]} = @(|*+)${tnode}:*PHYSUUID=${PUUID[tcnt]}:* ]] ||
			    node_do ${dnode} /opt/hpvm/bin/hpvmdevmgmt -m server:${tnode}:attr:PHYSUUID=${PUUID[tcnt]} ; then
			    : This set of updates all work as needed
			else
			    rtn=1
			    break 2
			fi
			let tcnt+=1
		    done
		    let dcnt+=1
		done
	    else
		rtn=1
		break
	    fi
	    fix=true
	else
	    break
	fi
    done
    return ${rtn}
}
#############################################################################
while getopts :P:Lm:QsV opt ; do
    case ${opt} in
	(P) # VM/Guest/Package Name as per hpvm
  	  PACKAGE=${OPTARG}
	;;
	(L) # Use Legacy packaging
	LEGACY=true
	;;
	(m) 
	if [[ ${OPTARG} = 1 ]] ; then
	    MAINTENANCE=true
	elif [[ ${OPTARG} = 0 ]] ; then
	    MAINTENANCE=false
	else
	    usage ${0} : Unknown maintenance mode option argument : ${OPTARG}
	fi
	;;
	(n) # nodes 1 per option as per SG
	NODES[${#NODES[*]}]=${OPTARG}
	;;
	(Q) # Quiet - Take defaults no interaction
	QUIET=true
	SANITY=false
	;;
	(s) # Sanity check don't do
	SANITY=true
	QUIET=false
	;;
	(V)
	VERBOSE=true
	;;
	(D)
	${DEBUG} && set -v
	DEBUG=true
	set -x
	;;
	(*) # Usage
	usage
	;;
    esac
done
shift OPTIND-1
# Check any remaining command arguments
while [[ -n ${1} ]] ; do
    if [[ -n ${PACKAGE} ]] then
	usage ${0} : Extra Package Argument : ${PACKAGE}
    else
	PACKAGE=${1}
    fi
    shift
done
PACKAGEDIR=${SGBASE}${PACKAGE}/
MAINTFILE=${PACKAGEDIR}MAINTENANCE_MODE_ENABLED
if [[ -n ${MAINTENANCE} ]] ; then
    # Maintenance Mode Command Option
    if [[ `cmviewcl -l package |  awk '$2~/up|down/{print $1}'` =  @(|*[[:space:]])${PACKAGE}@(|[[:space:]]*) &&
	-d ${PACKAGEDIR} ]] ; then
	if ${MAINTENANCE} ; then
	    if [[ -e ${MAINTFILE} ]] ; then
		Error Package already in Mainteance Mode : ${PACKAGE}
		exit 5
	    else
		if ! ${SANITY} ; then
		    if date +"%b %d %T ${0} `who -u`" > ${MAINTFILE} &&
			/opt/hpvm/bin/hpvmmodify -P ${PACKAGE} -F -i NONE >/dev/null 2>&1 &&
			/opt/hpvm/bin/hpvmmodify -P ${PACKAGE} -F -j 0 >/dev/null 2>&1 ; then
			${VERBOSE} && echo maintenance mode enabled for package : ${PACKAGE}
			exit 0
		    else
			Error Cannot enable maintenance mode for package : ${PACKAGE}
			exit 5
		    fi
		fi
	    fi
	else
	    if [[ -e ${MAINTFILE} ]] ; then
		if ! ${SANITY} ; then
		    if rm -f ${MAINTFILE} &&
			/opt/hpvm/bin/hpvmmodify -P ${PACKAGE} -F -i SG_${PACKAGE} >/dev/null 2>&1 &&
			/opt/hpvm/bin/hpvmmodify -P ${PACKAGE} -F -j 1 >/dev/null 2>&1 ; then
			${VERBOSE} && echo maintenance mode disabled for package : ${PACKAGE}
			exit 0
		    else
			Error Cannot disable maintenance mode for package : ${PACKAGE}
			exit 5
		    fi
		fi
	    else
		Error Package is NOT currently in Mainteance Mode : ${PACKAGE}
		exit 5
	    fi
	fi
    else
	Error The selected Serviceguard Package does not exist : ${PACKAGE}
	return 1
    fi
else
    # Package the Virtual Machine
    if ${QUIET} || intro ; then
	if get_and_check ; then
	    if get_backingstore ; then
		if ! ${SANITY} ; then
		    if package_configure ; then
			if remote_configure ; then
			    ${QUIET} || cat <<EOF

Please see the HP Integrity Virtual Machines documentation for additional
instructions on configuring Virtual Machines as Serviceguard packages.

Before running this package the following steps may need to be performed:

1. Review the configuration files located in ${PACKAGEDIR}.
2. Add new LVM Volume Groups to the cluster configuration file.
3. Check the cluster and/or package configuration using the cmcheckconf command.
4. Apply the cluster and/or package configuration using the cmapplyconf command.
5. If it is running, stop the virtual machine using: hpvmstop -F -P ${PACKAGE}
6. Umount filesystems and deactivating volume groups used by the virtual machine
7. Start the package using: cmrunpkg ${PACKAGE}

EOF
			    exit 0
			else
			    exit 3
			fi
		    else
			exit 3
		    fi
		fi
	    else
		exit 1
	    fi
	else
	    exit 1
	fi
    else
	exit 1
    fi
fi
