#!/bin/ksh
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
# bos72L src/bos/usr/lib/nim/methods/nim_master_setup.sh 1.18.4.1 
#  
# Licensed Materials - Property of IBM 
#  
# Restricted Materials of IBM 
#  
# COPYRIGHT International Business Machines Corp. 2001,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 
# @(#)51      1.18.4.1  src/bos/usr/lib/nim/methods/nim_master_setup.sh, cmdnim, bos72L, l2017_30A5 7/25/17 14:33:13
#
#   COMPONENT_NAME: CMDNIM
#
#   FUNCTIONS: ./usr/lib/nim/methods/nim_master_setup.sh
#
#   ORIGINS: 27
#
#
#   (C) COPYRIGHT International Business Machines Corp. 1993
#   All Rights Reserved
#   Licensed Materials - Property of IBM
#   US Government Users Restricted Rights - Use, duplication or
#   disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
#


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

# Set PROGRAM_NAME variable for error reporting.
PROGRAM_NAME="nim_master_setup"

# -------------------------------- module globals
backup="yes"
base_media=""
bosinst_data=""
cd_lpp=""
create_only=""
device=""
disk=""
file_system=""
create_fs="yes"
lpp_define="yes"
mk_resource=""
new_res=""
resolv_conf=""
volume_group=""
LOG="/var/adm/ras/nim.setup"
EZLOG="/var/adm/ras/eznim.cfg"
EZLOG_BK="/var/adm/ras/eznim.cfg.bk"
CD_MNT_DIR="/tmp/picaso_mnt_pt"
# --------------------------------------------------------------------------- #


#
# ------------------------------------- ck_vg
# NAME: ck_vg
#
# FUNCTION: Checks for volume group existence - creates one if necessary
#
# -------------------------------------------------------------------------- #
function ck_vg {

	# check for ${volume_group}
	# -   not found ? create it
	/usr/sbin/lspv | /usr/bin/grep "${volume_group}" >/dev/null 2>&1
	if [[ $? -ne 0 ]]; then

		if [[ -z ${disk} ]]; then
			# find next empty disk
			disk=`/usr/sbin/lspv | /usr/bin/grep None | /usr/bin/awk -F" " 'NR==1{print $1}' 2>/dev/null`
			# we should now have a physical volume
			if [[ -z ${disk} ]]; then
				${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_ERR_LOCATE_VOL} 'Error locating empty physical volume - Exiting.\n' \
					| /usr/bin/tee -a ${LOG}
				exit 1
			else
				${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_CREATE_VOL} 'Creating %s on next available physical volume %s...' ${volume_group} ${disk} \
					| /usr/bin/tee -a ${LOG}
			fi
		
		fi

		# create vg
		/usr/sbin/mkvg -f -y"${volume_group}" ${disk} >/dev/null 2>&1
		[ $? -ne 0 ] && \
		  ${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_ERR_DEFINE_VOL} 'Error defining %s volume group on %s - Exiting.\n' ${volume_group} ${disk} \
	                | /usr/bin/tee -a ${LOG} \
                   && exit 1
		
		${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_DONE} 'done\n' | /usr/bin/tee -a ${LOG}
	else
		# volume group already exists
		${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_LOCATE_VOL} 'Located volume group %s.\n' ${volume_group} | /usr/bin/tee -a ${LOG}
	fi

	return 0
}

# ------------------------------------- ck_fs
# NAME: ck_fs
#
# FUNCTION: Checks for filesystem existence and required sizing (optional)
#
# -------------------------------------------------------------------------- #
function ck_fs {

    typeset fs_name=$1
    typeset actual_fs_name=""
    typeset -i space_need=$2
    typeset -i free_space=0
	
    # check for ${fs_name}
    # -   not found ? create it
    /usr/sbin/lsfs | /usr/bin/grep "${fs_name} " >/dev/null 2>&1
    if [[ $? -ne 0 ]] && [[ ${create_fs} = yes ]]; then

      ${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_CREATE_FS} 'Creating %s filesystem...' ${fs_name} | /usr/bin/tee -a ${LOG}

      # find vfs type
      fs_type=`/usr/bin/grep defaultvfs /etc/vfs | /usr/bin/cut -f2 -d"	"`
      /usr/sbin/crfs -v ${fs_type} -g ${volume_group} -a size=${space_need} \
          -m ${fs_name} -A yes -p rw >/dev/null 2>&1

      [ $? -ne 0 ] && \
          ${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_ERR_CREATE_FS} 'Error creating %s filesystem - Exiting.\n' ${fs_name} \
                    | /usr/bin/tee -a ${LOG} \
                   && exit 1
      /usr/sbin/mount ${fs_name}
      [ $? -ne 0 ] && \
           ${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_ERR_MOUNT_FS} 'Error mounting %s filesystem - Exiting.\n' ${fs_name} \
                    | /usr/bin/tee -a ${LOG} \
                   && exit 1
    else
      #create fs only ? exit
      [[ -n ${create_only} ]] && return 0

      # may need to find actual fs name
      actual_fs_name="$( /usr/bin/df ${fs_name} | /usr/bin/awk 'NR==2{print $7}' 2>/dev/null )"

      /usr/sbin/mount | /usr/bin/grep "${actual_fs_name} " >/dev/null 2>&1
      [[ $? -ne 0 ]] && /usr/sbin/mount ${actual_fs_name}

      # make sure ${fs_name} has desired space (${space_need})
      ${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_SPACE_FS} 'Checking %s space requirement...' ${actual_fs_name} | /usr/bin/tee -a ${LOG}

      # expand filesystem
      free_space="$( /usr/bin/df ${actual_fs_name} | /usr/bin/awk 'NR==2{print $3}' 2>/dev/null )"
      if (( free_space < space_need )); then
          /usr/sbin/chfs -a size=+$(( space_need - free_space )) ${actual_fs_name} >/dev/null 2>&1
          [ $? -ne 0 ] && \
               ${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_ERR_EXP} 'Error expanding %s directory - Exiting.\n' ${actual_fs_name} \
                        | /usr/bin/tee -a ${LOG} \
                       && exit 1
      fi
    fi
	${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_DONE} 'done\n' | /usr/bin/tee -a ${LOG}

    return 0
}

#
# ------------------------------------- create_sysb
# NAME: create_sysb
#
# FUNCTION: Create system backup image
#
# -------------------------------------------------------------------------- #
function create_sysb {

	typeset -i MAX_SPACE_REQ=0
	typeset -i USED=0

	# exclude ${file_system} fs from backup
	echo "^.${file_system}/" >/etc/exclude.rootvg
	echo "^./tftpboot/" >>/etc/exclude.rootvg

	# get amount of space required
	# for the mksysb image
	/usr/sbin/lsvg -l rootvg | /usr/bin/grep jfs | /usr/bin/grep -v "N\/A" | 
	/usr/bin/grep -v "${file_system}" | /usr/bin/grep -v "\/tftpboot" | 
	/usr/bin/grep -v "closed" | /usr/bin/awk '{print $7}' |
	while read filesystem
	do
        # get the used space in each filesystem
        # (in 1024-byte blocks)
        let USED=$( /usr/bin/df -IM $filesystem | /usr/bin/tail +2l | /usr/bin/awk '{print $4}' )
        let MAX_SPACE_REQ=`expr $MAX_SPACE_REQ + $USED`
	done
	[[ -z "${MAX_SPACE_REQ}" ]] && \
	  ${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_ERR_CALC_SB} 'Error calculating space requirement for mksysb.\n' |
		 /usr/bin/tee -a ${LOG} && exit 1

	# add fudge factor
	let MAX_SPACE_REQ=`expr $MAX_SPACE_REQ + 65536`

	# create ${file_system} fs
	ck_fs ${file_system} ${MAX_SPACE_REQ}

	# create resource location for mksysb image
	/usr/bin/mkdir -p ${file_system}/mksysb

	# perform system backup
	/usr/bin/mksysb -X -e ${file_system}/mksysb/generic_sysb 

	# if creating image fails, remove backup flag
	# -    no mksysb resource to define
	if [ $? -ne 0 ]; then
	  ${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_ERR_CREATE_SB} 'Error creating system backup image.\n' | /usr/bin/tee -a ${LOG}
	  ${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_NO_CREATE_SB} 'No mksysb resource will be created.\n' | /usr/bin/tee -a ${LOG}
	  backup=""
	fi

    return 0
}

# ------------------------------------- nim_master_setup
#
# NAME: nim_master_setup
#
# FUNCTION:	 Initializes the NIM master and defines install resources
#
# NOTES:
#
#   This script will install the NIM master fileset (bos.sysmgt.nim.master)
#   and configure the NIM environment.  Once configured, install resources
#   will be created for environment usage.
#
#   The following outline gives an overview:
#     1) Environment setup options are determined
#        - default device is /dev/cd0
#        - default volume group is rootvg
#        - default filesystem is /export/nim
#        All options are overwritten based on cmd line parameters
#     2) Backup software is installed
#        - needed for creating mksysb image
#     3) /tmp filesystem must exist
#        - needs 8MB space
#     4) NIM master is configured
#        - tcpip must be configured
#        - supported network types are ethernet/token ring
#     5) image.data file is created (excludes nim resource filesystem)
#        - used for mksysb creation
#     6) nim resource filesystem must exist - create it
#        - needs 1GB space
#     7) /tftpboot filesystem must exist - create it
#        - needs 32MB of space
#     8) Default resources are created
#        - mksysb resource
#        - resolv_conf resource
#        - bosinst_data resource
#        - lpp_source resource
#        - spot resource
#     9) Easy lpar setup/install operations
#        - create resource group for lpar installs
#        - copy client.defs config file into nim resource filesystem
#
#    *) All stdout is also logged in location /var/adm/ras/nim.setup
#
# RETURNS: (int)
#	0	= SUCCESS
#	1	= FAILURE
#
# --------------------------------------------------------------------------- #
# 

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

		a)		# validate the attr ass
				# is it in the correct format (<var>=<value>)?
				if [[ "${OPTARG}" != +(?)=+(?) ]]; then
				   ${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_BAD_ARG} 'Bad argument assignment : %s\n.' ${OPTARG}
				   exit 1
				fi
				
				# separate variable from value
				variable=${OPTARG%%=*}
				value=${OPTARG#*=}

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

		B)		# do not create backup image
				backup=""
				;;
		
		F)		# do not create file system
				create_fs=""
				;;
		
		L)		# do not create lpp_source resource
				cd_lpp="yes"
				;;
		
		v)		# verbose mode (for debugging)
				set -x
				for i in $(typeset +f)
				do
					typeset -ft $i
				done
				;;

		\?)		# unknown option
				${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_NIM_MASTER_SETUP_USAGE} 'Usage nim_master_setup: Setup and configure NIM master.\nnim_master_setup [-a mk_resource={yes|no}]\n                       [-a file_system=<fs name>]\n                       [-a volume_group=<vg name>]\n                       [-a disk=<disk name>]\n                       [-a device=<device>] [-B] [-v]\n\n-B    Do not create mksysb resource.\n-v    Enable debug output.\n\nDefault values:\nmk_resource = yes\nfile_system = /export/nim\nvolume_group = rootvg\ndevice = /dev/cd0\n'
				exit 1
				;;
	esac
done


# touch log file - /var/adm/ras/nim.setup 
> ${LOG}

# touch config file - /var/adm/ras/eznim.cfg
# -  save off the original in case of error
if [[ -s ${EZLOG} ]]; then
  ${MV} ${EZLOG} ${EZLOG_BK}
fi
> ${EZLOG}

# informational banner
#
${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_NIM_MASTER_SETUP} '\n############################## NIM master setup ##############################\n#                                                                            #\n#  During script execution, lpp_source and spot resource creation times      #\n#  may vary. To view the install log at any time during nim_master_setup,    #\n#  run the command: tail -f /var/adm/ras/nim.setup in a separate screen.     #\n#                                                                            #\n##############################################################################\n'

# readme
/usr/bin/sleep 10

if [[ ${backup} = yes ]]; then
  # create image.data file
  ${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_CREATE_IMG_DATA} 'Creating image.data file...' | /usr/bin/tee -a ${LOG}
  /usr/bin/mkszfile -X 2>/dev/null
  [ $? -ne 0 ] && \
  ${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_ERR_CREATE_IMG_DATA} 'Error creating image.data file for mksysb.\n' | /usr/bin/tee -a ${LOG} \
  || ${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_DONE} 'done\n' | /usr/bin/tee -a ${LOG}
fi

# get device name from cmd line arg
# -   default value is /dev/cd0
typeset device="${device:-/dev/cd0}"
if [[ $device != /dev/cd[0-9]* ]] &&  [[ $device != /dev/usbms[0-9]* ]]; then
        cd_lpp=""
fi
if [[ $device = .* ]]; then
   device=`pwd`${device##.}
fi

${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_DEV_LOCATION} '\nDevice location is %s\n' ${device} | /usr/bin/tee -a ${LOG}
/usr/bin/sleep 1

# if cd_lpp is set, then assign device location as value
# -   used later when not defining an lpp_source
if [[ -n ${cd_lpp} ]]; then
  typeset cd_lpp="${device}"
  lpp_define=""
fi

# get vg name from cmd line arg
# -   default value is rootvg
typeset volume_group="${volume_group:-rootvg}"
${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_RES_VG_LOCATION} 'Resources will be defined on volume group %s\n' ${volume_group} | /usr/bin/tee -a ${LOG}
echo "export EZNIM_VG=${volume_group}" >>${EZLOG}
/usr/bin/sleep 1

# get fs name from cmd line arg
# -   default value is /export/nim
#     chop '/' from end of path
file_system=${file_system%/}      # we WILL NOT use '/' for expanding
typeset file_system="${file_system:-/export/nim}"
${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_RES_FS_LOCATION} 'Resources will exist in filesystem %s\n' ${file_system} | /usr/bin/tee -a ${LOG}
echo "export EZNIM_FS=${file_system}" >>${EZLOG}
/usr/bin/sleep 1


# system backup software - mksysb
# -   check for bos.sysmgt.sysbr 
# -   not found ? install it
${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_CK_SYSB_SW} 'Checking for backup software...' | /usr/bin/tee -a ${LOG}
/usr/bin/lslpp -l bos.sysmgt.sysbr >/dev/null 2>&1

if [[ $? -ne 0 ]]; then
  echo "." | /usr/bin/tee -a ${LOG}
  installp -acgqXd ${device} bos.sysmgt.sysbr >> ${LOG} 2>&1
  if [[ $? -ne 0 ]]; then
    ${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_ERR_SYSB_SW} 'Error installing system backup software - Exiting.\n' | /usr/bin/tee -a ${LOG} 
	exit 1
  fi
else
  ${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_ALREADY_INSTALLED} 'already installed\n' | /usr/bin/tee -a ${LOG}
fi

umask 022

# check /tmp dir
ck_fs /tmp 16384

# install NIM master fileset
# -   check for bos.sysmgt.nim.master
# -   not found ? install it
${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_INSTALL_MASTER_FILESET} 'Installing NIM master fileset...' | /usr/bin/tee -a ${LOG}
/usr/bin/lslpp -l bos.sysmgt.nim.master >/dev/null 2>&1

if [[ $? -ne 0 ]]; then
  echo "." | /usr/bin/tee -a ${LOG}
  installp -acgqXd ${device} bos.sysmgt.nim.master | /usr/bin/tee -a ${LOG}
  [ ! -e /usr/sbin/nimconfig ] && \
    ${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_ERR_INSTALL_MASTER_FILESET} 'Error installing NIM master fileset - Exiting.\n' \
	| /usr/bin/tee -a ${LOG} \
	&& exit 1
else
  ${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_ALREADY_INSTALLED} 'already installed\n' | /usr/bin/tee -a ${LOG}
fi

# configure the NIM environment
# -   obtain platform|kernel|interface info
# -   make default route
/usr/sbin/lsnim >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
  hostname=`/usr/bin/hostname -s`
  plat=`/usr/sbin/bootinfo -p`
  kern="64"
  # interfaces may have similar strings in their address
  pif=`/usr/bin/netstat -if inet | awk -v cmp=${hostname} '{
    split($4,ar,".")
    if ( cmp == ar[1] ) {
      print $1
    }
  } '`

  if [[ ${pif} = tr* ]]; then
	ring_speed=`/usr/sbin/mktcpip -S ${pif} 2>&1 | \
	  /usr/bin/awk 'BEGIN { RS="\n"; FS=":" } \
	  { for (i=1;i<=NF;i++) \
	  { if ( match($i,/speed/) ) (j=i) } \
	  if (NR==2) {print $j} }'`
	  type="-a ring_speed1=${ring_speed}";

  elif [[ ${pif} = e[nt]* ]]; then
	cable_type=`/usr/sbin/mktcpip -S ${pif} 2>&1 | \
	  /usr/bin/awk 'BEGIN { RS="\n"; FS=":" } \
	  { for (i=1;i<=NF;i++) \
	  { if ( match($i,/type/) ) (j=i) } \
	  if (NR==2) {print $j} }'`
	  type="-a cable_type1=${cable_type}";

  else
      ${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_ERR_DETERMINE_NET} 'Error determining network type.\n' | /usr/bin/tee -a ${LOG}
      ${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_SETUP_NET_SUPPORT} 'Easy setup only supports ethernet or token-ring networks - Exiting.\n' \
	  | /usr/bin/tee -a ${LOG}
      exit 1
  fi

  # define the NIM master
  ${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_DEFINE_MASTER} 'Defining NIM master...\n' | /usr/bin/tee -a ${LOG}
  /usr/sbin/nimconfig  -a netname=master_net -a pif_name=${pif} ${type} \
      -a platform=${plat} -a netboot_kernel=${kern}

  # add default route to master's network
  def_rt=`/usr/sbin/mktcpip -S ${pif} 2>&1 | /usr/bin/awk -F":" ' { if (NR == 2) {print $7} } '`
  /usr/sbin/lsnim -a routing1 master_net 2>&1 | grep default >/dev/null
  if [[ $? -eq 1 ]]; then
      /usr/sbin/nim -o change -a routing1="default ${def_rt}" master_net
  fi
fi


# Create resources?
if [[ ${mk_resource} != no ]]; then
  

  # set global var for fs creation ONLY (no size ck)
  create_only="yes"

  # create volume group for resources
  # -  (may already exist)
  ck_vg 

  # create the NIM resources location
  # create resources fs
  ck_fs ${file_system} 2949120

  # create /tftpboot fs
  ck_fs /tftpboot 65536 

  # allow size ck
  create_only=""

  # create/define a few NIM resources
  #
  # mksysb - from source ${file_system}/mksysb/generic_sysb
  # first  - obtain naming prefix for mksysb
  prefix=`${OSLEVEL} -r 2>/dev/null`
  version=`echo $prefix | /usr/bin/cut -c1`
  release=`echo $prefix | /usr/bin/cut -c2`
  mksysb_name="${prefix}master_sysb"
  echo "export EZNIM_SYSB=${mksysb_name}" >>${EZLOG}

  /usr/sbin/lsnim ${mksysb_name} >/dev/null 2>&1
  if [[ $? -ne 0 ]] && [[ ${backup} = yes ]]; then

     # atempt to create backup image
     create_sysb
     if [[ ${backup} = yes ]]; then
         # create mksysb_res
         ${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_CREATE_RES} 'Creating %s resource %s...' "mksysb" ${mksysb_name} | /usr/bin/tee -a ${LOG}
         /usr/sbin/nim -o define -t mksysb -a server=master \
            -a location=${file_system}/mksysb/generic_sysb \
            ${mksysb_name} >>${LOG} 2>&1

		 ${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_DONE} 'done\n' | /usr/bin/tee -a ${LOG}

		 new_res="${new_res} ${mksysb_name}"
     fi
  fi
 

  # resolv_conf file
  /usr/sbin/lsnim master_net_conf >/dev/null 2>&1
  if [[ $? -ne 0 ]] && [[ -s /etc/resolv.conf ]]; then
    ${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_CREATE_RES} 'Creating %s resource %s...' "resolv_conf" "master_net_conf" | /usr/bin/tee -a ${LOG}
	/usr/bin/mkdir -p ${file_system}/resolv_conf
    /usr/bin/cp /etc/resolv.conf ${file_system}/resolv_conf/resolv.conf
    /usr/sbin/nim -o define -t resolv_conf -a server=master \
        -a location=${file_system}/resolv_conf/resolv.conf master_net_conf
	[[ $? -eq 0 ]] && resolv_conf="yes"
	${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_DONE} 'done\n' | /usr/bin/tee -a ${LOG}
    
	new_res="${new_res} master_net_conf"
  fi


  # bosinst_data file - Default,no prompt,overwrite,no RDA,license_accept
  bid_ow=${prefix}bid_ow
  /usr/sbin/lsnim ${bid_ow} >/dev/null 2>&1
  if [[ $? -ne 0 ]] && [[ -s /usr/lpp/bosinst/bosinst.template ]]; then
	${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_CREATE_RES} 'Creating %s resource %s...' "bosinst_data" ${bid_ow} | /usr/bin/tee -a ${LOG}
	/usr/bin/mkdir -p ${file_system}/bosinst_data
    /usr/bin/sed 's/CONSOLE = .*/CONSOLE = Default/; s/INSTALL_METHOD = .*/INSTALL_METHOD = overwrite/; s/PROMPT = .*/PROMPT = no/; s/EXISTING_SYSTEM_OVERWRITE = .*/EXISTING_SYSTEM_OVERWRITE = yes/; s/RECOVER_DEVICES = .*/RECOVER_DEVICES = no/; s/ACCEPT_LICENSES = .*/ACCEPT_LICENSES = yes/; s/DESKTOP = .*/DESKTOP = NONE/' /usr/lpp/bosinst/bosinst.template >${file_system}/bosinst_data/${bid_ow}
    /usr/sbin/nim -o define -t bosinst_data -a server=master \
        -a location=${file_system}/bosinst_data/${bid_ow} ${bid_ow}
	[[ $? -eq 0 ]] && bosinst_data="yes"
	${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_DONE} 'done\n' | /usr/bin/tee -a ${LOG}

    new_res="${new_res} ${bid_ow}"
  fi


  # Create the default resource names for lpp_source and spot
  # -   lets get the vrmf from $device locale
  if `/usr/bin/mkdir -p ${CD_MNT_DIR}`; then
	while [[ $base_media != found ]]; do

	cd_media="directory"
	vrmf=""
	CDCHECKRC=-1
	MOUNTRC=-1
	if [[ ${device%%/cd*} = /dev ]] || [[ ${device%%/usbms*} = /dev ]]; then

		cd_media="device"
		${CDCHECK} -aq ${device} 2>/dev/null 1>&2  # check if device is managed by cdromd
		if [[ $? -eq 0 ]]; then
                 ${CDCHECK} -m -q ${device} 2>/dev/null 1>&2 # check if device is mounted	
			  if [[ $? -ne 0 ]]; then
                          ${CDMOUNT} -m ${device} >>${LOG} 2>&1 # mount device if not mounted
                 fi
                 CD_MNT_DIR=`${CDCHECK} -m -q ${device} 2>/dev/null` # get its mount point
			  CDCHECKRC=$?	
		fi

		if [[ $CDCHECKRC -ne 0 ]]; then
                 /usr/sbin/mount -rv cdrfs ${device} ${CD_MNT_DIR} >>${LOG} 2>&1
                 MOUNTRC=$?
		fi
		
		if [[ $MOUNTRC -eq 0 ]] || [[ $CDCHECKRC -eq 0 ]]; then
			if [[ -e ${CD_MNT_DIR}/installp/ppc/bos ]] ||
			   [[ -e ${CD_MNT_DIR}/bos ]]; then
			       base_media="found"
			fi

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

			# unmount
			if [[ $MOUNTRC -eq 0 ]]; then
			     /usr/sbin/umount ${CD_MNT_DIR} >/dev/null 2>&1
			fi
		fi
	else

		# The following code checks that the source directory contains base
		# images (not update images) by checking for the "bos" file.
		# If an lpp_source will be created from a directory, then check
		# that the bos.usr fileset exists.
		if [[ -e "${device}/installp/ppc/bos" ]] ||
		   [[ -e "${device}/bos" ]]; then
		      base_media="found"
		elif [[ -z $cd_lpp ]]; then
			if ls ${device}/installp/ppc 2>/dev/null | grep bos.usr* >/dev/null 2>&1
			then
				base_media="found"
			elif ls ${device} | grep bos.usr* >/dev/null 2>&1
			then
				base_media="found"
			fi
		fi

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

	# was product media located ? continue : ask again
	if [[ $base_media != found ]]; then
		echo ""
		[[ $cd_media = "device" ]] && \
			${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_PRODUCT_MEDIA} '\nPlease insert AIX %s product media in device %s\n' $version.$release $device
		${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_CK_LOCATION} 'If the location for AIX %s product media differs from\n%s %s, supply the absolute path BEFORE pressing the ENTER key.\n' $version.$release ${cd_media} $device
		read response?'=> '
		device="${response:-$device}"

		# attempt to read the media
		/usr/bin/sleep 10
	fi
	done
	# remove mount point
	/usr/bin/rm -r /tmp/picaso_mnt_pt >/dev/null 2>&1	
  fi

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


  # lpp_source - from source location $device
  /usr/sbin/lsnim ${def_lpp} >/dev/null 2>&1
  if [[ $? -ne 0 ]] && [[ -z ${cd_lpp} ]]; then
	# check ${file_system} fs
	ck_fs ${file_system} 1331200

	# create lpp_res
	${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_CREATE_RES} 'Creating %s resource %s...' "lpp_source" ${def_lpp} | /usr/bin/tee -a ${LOG}
    /usr/sbin/nim -o define -t lpp_source -a server=master \
        -a location=${file_system}/lpp_source/${def_lpp} \
        -a source=${device} ${def_lpp} >>${LOG} 2>&1
	${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_DONE} 'done\n' | /usr/bin/tee -a ${LOG}

	new_res="${new_res} ${def_lpp}"
  fi
  echo "export EZNIM_LPP=${def_spot}" >>${EZLOG}


  # remove any leftover spot  - (possibly bad resource)
  /usr/sbin/lsnim ${def_spot} >/dev/null 2>&1
  if [[ $? -eq 0 ]]; then

	Rstate=`/usr/sbin/lsnim -a Rstate ${def_spot} | /usr/bin/grep "Rstate" | /usr/bin/cut -f2 -d=`
	if [[ $Rstate != " ready for use" ]]; then
		/usr/sbin/nim -o remove ${def_spot} >>${LOG} 2>&1
		[[ $? -ne 0 ]] && \
		${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_ERR_RM_SPOT} 'Unable to remove existing SPOT resource %s\n' ${def_spot} \
		&& exit 1
	fi
  fi

  # spot - from source lpp_res
  /usr/sbin/lsnim ${def_spot} >/dev/null 2>&1
  if [[ $? -ne 0 ]]; then
	# check ${file_system} & /tftpboot fs
	ck_fs ${file_system} 720896
	ck_fs /tftpboot 65536

	# create spot_res
	${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_CREATE_RES} 'Creating %s resource %s...' "spot" ${def_spot} | /usr/bin/tee -a ${LOG}
    /usr/sbin/nim -o define -t spot -a server=master \
        -a location=${file_system}/spot \
        -a source=${cd_lpp:-$def_lpp} \
        ${def_spot} >>${LOG} 2>&1
	rc=$?
	${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_DONE} 'done\n' | /usr/bin/tee -a ${LOG}

	[ $rc -ne 0 ] && \
	${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_ERR_DEFINE_SPOT} 'SPOT define may have produced errors,\n\tplease check log %s for any instances.\n' ${LOG}

    new_res="${new_res} ${def_spot}"
  fi
  echo "export EZNIM_SPOT=${def_spot}" >>${EZLOG}


  # create a basic resource group for bos install operation on clients
  /usr/sbin/lsnim basic_res_grp > /dev/null 2>&1
  if [[ $? -ne 0 ]]; then
	${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_CREATE_RES_GRP} 'Creating resource group %s...' "basic_res_grp" | /usr/bin/tee -a ${LOG}
	/usr/sbin/nim -o define -t res_group ${bosinst_data:+-a bosinst_data=$bid_ow} \
		${backup:+-a mksysb=$mksysb_name} ${lpp_define:+-a lpp_source=$def_lpp} \
		-a spot=${def_spot} ${resolv_conf:+-a resolv_conf=master_net_conf} basic_res_grp >> ${LOG} 2>&1
		${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_DONE} 'done\n' | /usr/bin/tee -a ${LOG}

  elif [[ -n ${new_res} ]]; then
	${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_ADD_RES_MEMBER} 'Adding newly created resources to %s...' "basic_res_grp" | /usr/bin/tee -a ${LOG}
	for mbr in ${new_res}
	do
	    /usr/sbin/nim -o change -a add_member=${mbr} basic_res_grp >> ${LOG} 2>&1
		[[ $? -ne 0 ]] && \
		${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_ERR_CREATE_RES_GRP} 'Unable to add resource %s to %s\n\tplease check log %s for errors.\n' ${mbr} "basic_res_grp" ${LOG}
	done
	${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_DONE} 'done\n' | /usr/bin/tee -a ${LOG}
  fi

  # adding client.defs file to ${file_system}
  if [[ -s /usr/samples/nim/client.defs ]]; then
	/usr/bin/cp -i /usr/samples/nim/client.defs /export/nim

	# adding write perm to client.defs
    /usr/bin/chmod u+w /export/nim/client.defs >/dev/null 2>&1
  fi


  # Finished - lets recap
  ${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_RES_GRP_COMPLETE} '\nThe following resources now exist: \n' | /usr/bin/tee -a ${LOG}
  /usr/sbin/lsnim -c resources | /usr/bin/tee -a ${LOG}

fi

${DSPMSG} -s ${MSG_SET} cmdnim.cat ${MSG_NIM_SETUP_COMPLETE} '\nNIM master setup is complete - enjoy!\n' | /usr/bin/tee -a ${LOG}

exit 0
