#!/bin/ksh
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
# bos72L src/bos/usr/lib/nim/methods/mkcosi.sh 1.8.1.3 
#  
# Licensed Materials - Property of IBM 
#  
# COPYRIGHT International Business Machines Corp. 2006,2017 
# 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 
# @(#)86    1.8.1.3  src/bos/usr/lib/nim/methods/mkcosi.sh, cmdnim, bos72L, l2017_30A5  7/25/17  14:43:34
#
#   COMPONENT_NAME: CMDNIM
#
#   FUNCTIONS: ./usr/lib/nim/methods/mkcosi.sh
#
#   ORIGINS: 27
#

NIMPATH=/usr/lpp/bos.sysmgt/nim
NIM_METHODS="${NIMPATH}/methods"
export NIMPATH NIM_METHODS
. ${NIM_METHODS}/c_sh_lib
. ${NIM_METHODS}/libcosi

# --------------------------- module globals
devicetype=""
level=""
ARGUMENT=""
FILESYSTEM=""

# --------------------------------------------------------------------------- #
# NAME:         usage
#
# FUNCTION:     Print usage message
#
# PARAMETERS:   None.
#
# RETURNS:      0 - successful function execution
# --------------------------------------------------------------------------- #
function usage {

	/usr/bin/dspmsg -s ${MSG_SET} cmdnim.cat ${MSG_MKCOSI_USAGE} \
		'%1$s -s Source [-l Location] [-S Server] [-v] COSI\n' "${PROGNAME}"
	return 0
}

# --------------------------------------------------------------------------- #
# NAME:         ck_nim_env
#
# FUNCTION:     Checks for existing nim environment
#
# PARAMETERS:   None.
#
# RETURNS:      0 - nim environment exist
#               1 - unable to determine environment
# --------------------------------------------------------------------------- #
function ck_nim_env {

        /usr/bin/lslpp -l bos.sysmgt.nim.master >/dev/null 2>&1

        if [[ $? -ne 0 ]]; then
		nim_master_setup -B ${FILESYSTEM:+-a file_system=$FILESYSTEM} -a device=$source || return 1
		master_setup=1
	else
		#
		# Fileset exist, so determine if NIM is configure
		#
		ck_init || return 1
        fi

        return 0
}

# --------------------------------------------------------------------------- #
# NAME:         ck_init
#
# FUNCTION:     Checks if the NIM master is configured.
#
# PARAMETERS:   None.
#
# RETURNS:      0 - if the NIM master is configured.
#               1 - if the NIM master is not configured.
# --------------------------------------------------------------------------- #
function ck_init {

        ODMDIR=/etc/objrepos /usr/bin/odmget -q "name=master" nim_object 2>/dev/null |
                /usr/bin/grep master > /dev/null

	rc=$?

	if [[ $rc -ne 0 ]]; then
		/usr/bin/dspmsg -s ${MSG_SET} cmdnim.cat ${MSG_MASTER_NOT_CONFIGURED} \
                        'NIM master not configured.\n'
	fi

        if [[ $rc -ne 0 ]] || [[ ! -s /var/adm/ras/eznim.cfg ]]; then
		source_location=$source
		if [[ $devicetype = "nim" ]]; then
			source_location=`get_attr_value "master" $source "location"`
		fi
		nim_master_setup -B ${FILESYSTEM:+-a file_system=$FILESYSTEM} -a device=$source_location || return 1
		master_setup=1
        fi

        return 0
}

# --------------------------------------------------------------------------- #
# NAME:         ck_attr
#
# FUNCTION:     Check for valid attribute.
#
# PARAMETERS:   None.
#
# RETURNS:      0 - valid attribute
#               1 - invalid attribute
# --------------------------------------------------------------------------- #
function ck_attr {

	# Check the following global flag:
	# ARGUMENT
	# server
	# source
	# location

	ck_user || return 1

	if [[ -z $source ]] || [[ -z $ARGUMENT ]] || [[ $(echo $ARGUMENT | wc -w) -gt 1 ]]; then
		usage
		return 1
	fi

	if [[ -z $server ]]; then
		server="master"
	fi

	devicetype=`get_devicetype $source`
	if [[ $? -ne 0 ]]; then
		/usr/bin/dspmsg -s ${ERR_SET} cmdnim.cat ${ERR_SOURCE} \
			'0042-055 %s: \"%s\" is not a valid \"source\" for\n\tthis operation' \
			${PROGNAME} "${source}"
		echo
		return 1
	fi
	# cdrom devicetype is also given to usbms
	if [[ $devicetype = "cdrom" ]]; then
		source=`ck_source $source`  || return 1
	fi

        return 0
}

# --------------------------------------------------------------------------- #
# NAME:         define_cosi
#
# FUNCTION:     Define the dataless client.
#
# PARAMETERS:   None.
#
# RETURNS:      0 - nim environment exist
#               1 - unable to determine environment
# --------------------------------------------------------------------------- #
function define_cosi {

	typeset name=$1
	typeset server=$2
	typeset location=$3
	typeset source=$4
	
	# Determine the source.  
	# cdrom	 - Mount the cdrom, create a temporary lpp_source to create the common image.
	#          Once completed, unmount the cdrom and remove the lpp_source.
	#
	# dir	 - Create the lpp_source from the directory to create the common image.
	#          Once completed, remove the lpp_source.
	#
	# mnt	 - Create the lpp_source using the mounted location as a source to create the common image.
	#	   Once completed, remove the lpp_source and remove the content from the lpp_source location.
	#
	# nim	 - Create the common image from the NIM lpp_source object.
	#
	# remote - Mount the remote location, and create the lpp_source from the mounted location.
	#	   Once completed, remove the lpp_source and remove the content from the lpp_source location.
	if [[ -n $master_setup ]]; then
		# The spot name is derived the same as how nim_master_setup does it.
		# This way, we can get the spot name from nim_master_setup for renaming.

		source_location=$source
		if [[ $devicetype = "nim" ]]; then
			source_location=`get_attr_value "master" $source "location"`
		fi

                if [[ -e "${source_location}/OSLEVEL" ]]; then
                        vrmf=`/usr/bin/cat "${source_location}/OSLEVEL" | /usr/bin/cut -f2 -d'='`
                else
                        vrmf=`/usr/sbin/installp -Ld ${source_location} |
                                      /usr/bin/grep "bos.rte.install" | /usr/bin/cut -f3 -d:`
                fi

                vrmf=`echo ${vrmf} | /usr/bin/awk -F. '{print $1 $2 $3}' 2>/dev/null`
                common_image="${vrmf}spot_res"

		/usr/bin/dspmsg -s ${MSG_SET} cmdnim.cat ${MSG_RENAME_RES} \
			'Renaming resource from %1$s to %2$s.\n' "${common_image}" "${name}"
		/usr/sbin/nim -o change -a new_name=$name $common_image
	else
	        if [[ $devicetype = "dir" ]]; then
        	        define_res "lpp_source" "${name}_$$_lpp" $server "$location/${name}_$$_lpp" $source         || return 1
                	define_res "spot"        $name           $server  $location                "${name}_$$_lpp" || return 1
	                rm_nim_obj "${name}_$$_lpp"
			rm_file "$location/${name}_$$_lpp"

	        elif [[ $devicetype = "mnt" ]]; then
        	        define_res "lpp_source" "${name}_$$_lpp" $server "$location/${name}_$$_lpp" $source         || return 1
                	define_res "spot"        $name           $server  $location                "${name}_$$_lpp" || return 1
	                rm_nim_obj "${name}_$$_lpp"
        	        rm_file "$location/${name}_$$_lpp"
		#cdrom could also mean usbms
	        elif [[ $devicetype = "cdrom" ]]; then
                	define_res "lpp_source" "${name}_$$_lpp" $server "$location/${name}_$$_lpp" $source         || return 1
	                define_res "spot"        $name           $server  $location                "${name}_$$_lpp" || return 1
                	rm_nim_obj "${name}_$$_lpp"
			rm_file "$location/${name}_$$_lpp"

	        elif [[ $devicetype = "remote" ]]; then
        	        nim_mount $source
                	define_res "lpp_source" "${name}_$$_lpp" $server "$location/${name}_$$_lpp" $access_pnt     || return 1
	                define_res "spot"        $name           $server  $location                "${name}_$$_lpp" || return 1
	                nim_unmount $source
        	        rm_nim_obj "${name}_$$_lpp"
                	rm_file "$location/${name}_$$_lpp"
	
        	elif [[ $devicetype = "nim" ]]; then
	                define_res "spot" $name $server $location $source || return 1
	        fi
	fi

	return 0
}

# --------------------------------------------------------------------------- #
# NAME:         undo
#
# FUNCTION:     Remove the file that from NIM object location
#
# PARAMETERS:   None.
#
# RETURNS:      0 - file removed successfully
#               1 - unable to remove file
# --------------------------------------------------------------------------- #
function undo {

	if [[ $(obj_exist "master" "${name}_$$_lpp"; echo $?) -eq 0 ]]; then
		rm_nim_obj "${name}_$$_lpp"
	fi

	if [[ -s "$location/${name}_$$_lpp" ]]; then
		rm_file "$location/${name}_$$_lpp"
	fi

	err_signal

	return 1
}

# --------------------------------------------------------------------------- #
# NAME:         nim_init
#
# FUNCTION:     initializes the NIM environment for a shell script
#               Over-ride c_sh_lib nim_init so that we can continue if
#               /etc/niminfo file is not present.
#
# PARAMETERS:   None.
#
# RETURNS:      0 - successful
#               1 - unsuccessful
# --------------------------------------------------------------------------- #
function nim_init {

        typeset -i tmp_free=0

        # create a dir for tmp files
        # do this now, before anything else because other functions may be called
        #               which depend on this directory
        mk_tmp_dir

        # must have at least 5 meg of free space in /tmp
        tmp_free="$( ${DF} /tmp | ${AWK} 'NR==2{print $3}' 2>/dev/null )"
        (( ${tmp_free} < ${REQUIRED_TMP_SPACE} )) && \
                error ${ERR_SPACE} /tmp ${REQUIRED_TMP_SPACE} ${tmp_free}

        if [[ -s /SPOT/niminfo ]]; then
                . /SPOT/niminfo
        elif [[ -s ${NIMINFO} ]]; then
                # we're not currently executing in the network boot environment
                # use the version which is in the traditional place
                . ${NIMINFO}
        else
		/usr/bin/dspmsg -s ${MSG_SET} cmdnim.cat ${MSG_CMD_FILE_ACCESS} \
                        '%1$s: Unable to access the \"%2$s\" file.\n' "${PROGNAME}" "/etc/niminfo" 1>&2
                return 1
        fi

        return 0
}

# ---------------------------------- mkcosi --------------------------------- #
#
# NAME: mkcosi
#
# FUNCTION:	 /usr/sbin/mkcosi command 
#
# NOTES:
#
# RETURNS: (int)
#	0	= SUCCESS
#	1	= FAILURE
#
# --------------------------------------------------------------------------- #
#
trap cleanup 0
trap 'undo' 2 11 15

# NIM initialization
nim_init

# set parameters from command line
while getopts :S:l:s:v x
do
	case ${x} in

		S)	# Specify the server to store the common image.
			server=${OPTARG}
			;;

		l)	# Specify the path location to store the common image.
			location=${OPTARG}
			;;

		s)	# Specify the source for creating the common image.
			source=${OPTARG}
			;;

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

		\?)	# unknown option
			usage
			exit 1
			;;
	esac
done

shift $((OPTIND - 1))

ARGUMENT=$*

if [[ -z $location ]]; then
	if [[ -s /var/adm/ras/eznim.cfg ]]; then
                . /var/adm/ras/eznim.cfg
		location=${EZNIM_FS}/spot
		FILESYSTEM=${EZNIM_FS}
	else
		location=/export/eznim/spot
		directory=`/usr/bin/basename $location`
		FILESYSTEM="${location%%/$directory}"
	fi
else
	directory=`/usr/bin/basename $location`
	FILESYSTEM="${location%%/$directory}"
fi

ck_attr     || exit 1
ck_nim_env  || exit 1

if [[ $(obj_exist "master" $ARGUMENT; echo $?) -eq 0 ]]; then
        /usr/bin/dspmsg -s ${MSG_SET} cmdnim.cat ${MSG_CMD_EXISTS} \
                '%1$s: \"%2$s\" already exists.\n' "${PROGNAME}" "${ARGUMENT}"
        exit 1
fi

define_cosi "${ARGUMENT}" $server $location $source || exit 1
rc=$?
exit $rc

# end of script