#!/bin/ksh
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
# bos720 src/bos/usr/lib/nim/methods/c_mksavewpar.sh 1.1.1.1 
#  
# Licensed Materials - Property of IBM 
#  
# COPYRIGHT International Business Machines Corp. 2008,2013 
# 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 
# @(#)40 1.1.1.1 src/bos/usr/lib/nim/methods/c_mksavewpar.sh, cmdnim, bos720 1/22/13 16:09:27
#
#   COMPONENT_NAME: CMDNIM
#
#   FUNCTIONS: ./usr/lib/nim/methods/c_mksavewpar.sh
#
#

# include common NIM shell defines/functions
NIMPATH=${0%/*}
NIMPATH=${NIMPATH%/*}
[[ ${NIMPATH} = ${0} ]] && NIMPATH=/usr/lpp/bos.sysmgt/nim
NIM_METHODS="${NIMPATH}/methods"
. ${NIM_METHODS}/c_sh_lib

#---------------------------- local defines     --------------------------------
EXCLUDE_WPAR=""
SAVEWPAR=/usr/bin/savewpar
savewpar_mnt_dir=""

#---------------------------- module globals    --------------------------------
REQUIRED_ATTRS="location wpar" 
OPTIONAL_ATTRS="comments exclude_files group mk_image savewpar_flags verbose server" 
location=""
server=""
comments=""
exclude_files=""
group=""
mk_image=""
verbose=""



#---------------------------- process_exclude_file ----------------------------
#
# NAME: process_exclude_file 
#
# FUNCTION:  Sets up access to the exclude file that we are 
#            using and copies it to /etc/exclude.${wpar} so
#            that the savewpar command will use it when backing
#            up the system.  If a previous exclude file exists
#            it will be saved and restored after the backup. 
#
# EXECUTION ENVIRONMENT:
#
# NOTES:
#       calls error on failure
#
# RECOVERY OPERATION:
#
# DATA STRUCTURES:
#       parameters:
#       global:
#
# RETURNS: (int)
#       0 = success
#
# OUTPUT:
#-------------------------------------------------------------------------------
function process_exclude_file {

     # save the old exclude file 
     if [[ -f ${EXCLUDE_WPAR} ]]; then
          ${CP} ${EXCLUDE_WPAR} ${EXCLUDE_WPAR}.nim_save.$$ ||
               err_from_cmd "${CP} ${EXCLUDE_WPAR} ${EXCLUDE_WPAR}.nim_save.$$"
     fi

     # set up access to the exclude file 
     if [[ ${exclude_files} = ?*:?* ]]; then
          # mount remote exclude file 
          nim_mount ${exclude_files} 
          exclude_access=${access_pnt}
     else
          # exclude file is local
          exclude_access=${exclude_files} 
     fi 

     # put the exclude file in /etc/exclude.${wpar}
     # so that the savewpar command will read it
     ${CP} ${exclude_access} ${EXCLUDE_WPAR} ||
          err_from_cmd "${CP} ${exclude_access} ${EXCLUDE_WPAR}"

     nim_unmount ${access_pnt}

    # add the -e flag since we have successfully copied the exclude_files resource
    savewpar_flags=e${savewpar_flags}

} # end process_exclude_file

#---------------------------- format_savewpar_flags ----------------------------
#
# NAME: format_savewpar_flags 
#
# FUNCTION:  The options to savewpar_flags are "aANVXZab:aeimpv".  This function
#            makes sure that the flags are in the correct format to 
#            pass to savewpar no matter what order they are entered 
#			 by the user.
#
# EXECUTION ENVIRONMENT:
#
# NOTES:
# 		The -b option to savewpar takes a numeric argument.
# 		Make sure that there is a space after the -b flag
# 		and it's argument.  If not, savewpar will take everything
# 		after the -b flag as the block_size argument.
#
# RECOVERY OPERATION:
#
# DATA STRUCTURES:
#       parameters:
#       global:
#
# RETURNS: 
#
# OUTPUT:
#-------------------------------------------------------------------------------
function format_savewpar_flags {

     in_flags=${1}
     fmt_flags=""
     i=1

     # get number of characters in flags 
     num_flags=`${ECHO} ${in_flags} | ${WC} -c | ${AWK} '{print $1}'`

     # Loop through the flags and make sure that there is
     # a space after the -b flag and it's argument.
     while [[ $i -lt $num_flags ]]; do

          flag=`${ECHO} ${in_flags} | ${CUT} -c $i`

          # if digit print and set digit flag 
          if [[ "${flag}" = +([0-9]) ]]; then
               fmt_flags=${fmt_flags}`${ECHO} "${flag}\c"`
               isdigit=true

          # if not digit print savewpar flag
          elif [ ! "$isdigit" ]; then
               fmt_flags=${fmt_flags}`${ECHO} "${flag}\c"`
          else
               # last thing printed was a digit so
               # print space before next savewpar flag
               isdigit=

               # if space just print it
               if [[ "${flag}" = " " ]]; then
       	            fmt_flags=${fmt_flags}`${ECHO} " \c"`

               # if flag print with hyphen
               else
      	            fmt_flags=${fmt_flags}`${ECHO} " -${flag}\c"`
               fi

          fi

          let i=i+1

     done

     ${ECHO} ${fmt_flags}

} # end format_savewpar_flags

#---------------------------- c_mksavewpar_cleanup ----------------------------
#
# NAME: c_mksavewpar_cleanup 
#
# FUNCTION:  Replace the exclude file as it was before we ran
#            and call the generic cleanup function to make sure
#            everything gets unmounted.
#
# EXECUTION ENVIRONMENT:
#
# NOTES:
#       calls error on failure
#
# RECOVERY OPERATION:
#
# DATA STRUCTURES:
#       parameters:
#       global:
#
# RETURNS: 
#
# OUTPUT:
#-------------------------------------------------------------------------------
function c_mksavewpar_cleanup {

     # copy the old exclude file back
     if [[ -f ${EXCLUDE_WPAR}.nim_save.$$ ]]; then
          ${MV} ${EXCLUDE_WPAR}.nim_save.$$ ${EXCLUDE_WPAR} > /dev/null 2>&1 || 
               err_from_cmd "${MV} ${EXCLUDE_WPAR}.nim_save.$$ ${EXCLUDE_WPAR}"
     else
          # remove the exclude file we installed
          if [ -n "${exclude_files}" ] && [ -f "${EXCLUDE_WPAR}" ]; then
               ${RM} ${EXCLUDE_WPAR} || warning_from_cmd "${RM} ${EXCLUDE_WPAR}"
          fi
     fi

     # clean up the mount point if we mounted the savewpar write directory over.
     # we need to do this here since if the unmount fails the entire directory 
     # might get erased.  
     if [[ -n "${savewpar_mnt_dir}" ]]; then
          nim_unmount ${savewpar_mnt_dir}

          # Check to see if the unmount failed.  If it failed then
          # leave the temporary directory there.  We don't want to 
          # inadvertently erase extra files.
          ${MOUNT} | ${EGREP} -q ${savewpar_mnt_dir}
          if [[ $? -ne 0 ]]; then
                ${RM} -r ${savewpar_mnt_dir}
          fi
     fi

     cleanup

} # end c_mksavewpar_cleanup

#-------------------------------  MAIN  ---------------------------------------

# signal processing
trap c_mksavewpar_cleanup 0
trap err_signal 1 2 11 15

# NIM initialization
nim_init

# set parameters from command line
while getopts :a:qv c
do
     case ${c} in

          a)  # validate the attr ass
              parse_attr_ass "${OPTARG}"

              # include the assignment for use in this environment
              eval ${variable}=\"${value}\"
              ;;

          q)  # show attr info
              cmd_what
              exit 0
              ;;

          v)  # verbose mode (for debugging)
              set -x
              for i in $(typeset +f)
              do
                   typeset -ft $i
              done
              ;;

          \?) # unknown option
              error ${ERR_BAD_OPT} ${OPTARG}
              ;;
     esac
done

# check for missing attrs
ck_attrs

# check that bos.sysmgt.sysbr (System Backup and BOS Install Utilities) is installed 
STATE=`${LSLPP} -qcIL bos.sysmgt.sysbr 2>/dev/null | ${CUT} -d":" -f6`  

if [[ "${STATE}" != "C" ]]; then
     nim_name=`${GREP} NIM_NAME ${NIMINFO} | ${CUT} -d"=" -f2`
     error ${ERR_NO_SYSBR} ${nim_name}   
fi

# handle exclude file resource 
EXCLUDE_WPAR=/etc/exclude.${wpar}
[ -n "${exclude_files}" ] && process_exclude_file

# is this machine the image server?
if [[ -n "${server}" ]]; then
     # mount the remote location 
 
     # going to create a tmp directory at "/tmp/$$.mnt"
     # look for lowest, unused seqno
     typeset -i idx=0
     while (( ${idx} < ${MAX_MNT} ))
     do
          savewpar_mnt_dir="/tmp/$$.mnt${idx}"
          [[ ! -d ${savewpar_mnt_dir} ]] && break
          let idx=idx+1
     done
     (( ${idx} >= ${MAX_MNT} )) && error ${ERR_GEN_SEQNO} /tmp/$$.mnt

     ${MKDIR} ${savewpar_mnt_dir} 2>${ERR} || err_from_cmd ${MKDIR}

     nim_mount ${server}:`${DIRNAME} ${location}` ${savewpar_mnt_dir}
     location_access=${access_pnt}/`${BASENAME} ${location}`
else
     # location is local to this machine
     location_access=${location}
fi

# check savewpar_flags format and content
if [[ -n "${savewpar_flags}" ]]; then
     # put hyphens in front of all flags
     savewpar_flags=$( ck_installp_flags "${savewpar_flags}" )

     # make sure all flags are valid
     /usr/bin/getopt "ANVXab:eimpv" ${savewpar_flags} > /dev/null 2>&1 || 
          error ${ERR_BAD_SAVEWPAR_FLAG}

	  # verify that flags are in correct format
	  savewpar_flags=$( format_savewpar_flags "${savewpar_flags}" )
fi

# call savewpar to create the image
${SAVEWPAR} -f ${location_access} ${savewpar_flags} ${wpar} 2>&1

# exit with return code from savewpar
RC=$?

# all done
exit $RC
