
[ -z "$SI_CONFIG_DIR" ] && SI_CONFIG_DIR=/tmp/install_config
[ -z "$JS_MEDIA_DIR" ]  && JS_MEDIA_DIR=/tmp/install_media

[ -z "$JS_PATCH_DIR" ]  && JS_PATCH_DIR=$JS_MEDIA_DIR/Patches
[ -z "$JS_PKGS_DIR" ]   && JS_PKGS_DIR=$JS_MEDIA_DIR/Packages
[ -z "$JS_PLTF_DIR" ]   && JS_PLTF_DIR=$JS_MEDIA_DIR/Platforms

[ -z "$SID" ]           && SID=$SI_CONFIG_DIR
[ -z "$JSINCLUDE" ]     && JSINCLUDE=$SID/Scripts/Misc/!Includes
[ -z "$SI_PROFILE" ]    && SI_PROFILE=$SI_CONFIG_DIR/Profiles/Std
[ -z "$slash_a" ]       && slash_a=/a

BIN=$SID/bin
MISC=$SID/Scripts/Misc
export SI_CONFIG_DIR SID JSINCLUDE SI_PROFILE slash_a BIN MISC
export JS_MEDIA_DIR JS_PATCH_DIR JS_PKGS_DIR JS_PLTF_DIR

PKGADMIN="
  instance=overwrite
  partial=nocheck
  runlevel=nocheck
  idepend=nocheck
  rdepend=nocheck
  space=nocheck
  setuid=nocheck
  conflict=nocheck
  basedir=default
  action=nocheck
  mail=
"

PKGADMIN_FILE=/tmp/Admin
PKGADMIN_OPTS="-a $PKGADMIN_FILE"
export PKGADMIN PKGADMIN_FILE PKGADMIN_OPTS

MakeAdminFile() {
  mkdir -p `dirname $PKGADMIN_FILE`
  for i in $PKGADMIN ; do echo $i ; done >$PKGADMIN_FILE
}


TBL="\t"
RET="\n"
InformMe() { echo "${RET}${TBL}         \n${TBL}$1\n" ; return 0 ; }
NotifyMe() { echo "${RET}${TBL}NOTICE:  \n${TBL}$1\n" ; return 0 ; }
WarnMe()   { echo "${RET}${TBL}WARNING: \n${TBL}$1\n" ; return 1 ; }
CrashMe()  { echo "${RET}${TBL}ERROR: $1\n${TBL}Aborting\n"  ; exit 1   ; }
ShellMe()  { echo "${RET}${TBL}FATAL: $1\n${TBL}Starting Shell\n"  ; StartShell ; }

Yes()   {
  while true ; do
    echo "${TBL}\t$1\c :"
    read A </dev/tty
    echo $A | egrep -s '^j|^J|^Y|^y' && return 0
    echo $A | egrep -s '^n|^N'       && return 1
    echo "${TBL}\tBad answer, try again: y/n \n"
  done
}

ChrootMe() {
  [ -h /a ] && ShellMe "$0: Already chrooted"
  [ -h /a/a ] || ln -s . /a/a || ShellMe "Could not create /a/a symlink"
  [ -z "$1" ] && CMD="$SID/Scripts/Misc/StartShell From $0" || CMD="$*"
  chroot /a /bin/sh -c "$CMD"
  rm /a/a || ShellMe "Could not remove /a/a symlink"
}

MakePath() {
  #
  # Make a nice $PATH, avoiding duplicates
  #
  TP="" ; for i in `echo $PATH | sed 's/:/ /g'` ; do
    [ "$i" != $BIN   -a   "$i" != $MISC ] && TP="$TP:$i"
  done
  PATH=$BIN:$MISC$TP  ; export PATH
}

SetRootOpts() {
  #
  # Check whether we have chrooted to /a already
  #
  ROOT=/ ; ROOTOPTS=""
  [ ! -h /a   -a   -d /a/var/sadm/pkg   -a   -d /usr/sbin/install.d/install_config/. ] && {
    ROOT="/a"
    ROOTOPTS="-R /a"
    JS_ROOT_OPTS=$ROOTOPTS
  }
  export ROOT ROOTOPTS JS_ROOT_OPTS
}

FindRootDisk() {
  #
  # Complain about undetermined SI_ROOTDISK, but not in Begin script phase
  #
  [ -z "$SI_ROOTDISK"   -o   "$SI_ROOTDISK" = "." ] && {
    SI_ROOTDISK=`basename \`/sbin/mount | egrep "^$ROOT on /dev/.*dsk/" | head -1 | awk '{print $3}'\` | sed 's/s.$/s2/'`
  }
  [ -z "$SI_ROOTDISK"   -o   "$SI_ROOTDISK" = "." ] && {
    /usr/proc/bin/ptree $$ | grep -v grep | egrep -s Scripts/Begin || WarnMe "Can not determine SI_ROOTDISK"
  }
  export SI_ROOTDISK
}

FindNetInfo() {
  #
  # Figure out the primary interface and subnet
  # We define it only once at begginning, as /etc/hosts
  # and interfaces configurations may change later
  #
  [ -z "$MYNAME" ]      && MYNAME=`uname -n | cut -d. -f1`
  [ -z "$MYBASE" ]      && MYBASE=`uname -n | cut -d. -f1 | cut -d- -f1`
  [ -z "$MYADDR" ]      && MYADDR=`grep -v '^#' /etc/hosts | awk '{if($2=="'\`uname -n\`'") print $1}' | head -1`
  [ -z "$MYADDR" ]      && MYADDR=`netstat -in | awk '$1~/^[a-z].*[0-9]$/' | sort -k5 -nr | awk '{print $4}' | head -1`
  [ -z "$PRIMARY_IFC" ] && PRIMARY_IFC=`netstat -in | awk '{if($4=="'$MYADDR'") print $1}' | head -1`
  [ -z "$PRIMARY_NET" ] && PRIMARY_NET=`netstat -in | awk '{if($4=="'$MYADDR'") print $3}' | head -1`

  export MYADDR MYBASE MYNAME PRIMARY_IFC PRIMARY_NET

  JS_MYADDR=$MYADDR
  JS_MYBASE=$MYBASE
  JS_MYNAME=$MYNAME
  JS_PRIMARY_IFC=$PRIMARY_IFC
  JS_PRIMARY_NET=$PRIMARY_NET

  export JS_MYADDR JS_MYBASE JS_MYNAME JS_PRIMARY_IFC JS_PRIMARY_NET

  [ -z "$SI_HOSTNAME" ] && SI_HOSTNAME=$MYNAME
  export SI_HOSTNAME

}


FindSiteName() {
  #
  # Search for pieces of profile (DiskSlicing, Packages, Finish etc.)
  # named same as hostname. Figure out the $SITE from path to such pieces
  #
  # Failing that, assume AnySite (which still may be a softlink to our site)
  # and take Std profile pieces from there
  #
  [ -n "$SITE" ] && return 0
  INCDIR=`dirname $SI_PROFILE`
  INCLIST=`find $INCDIR | grep -v /SiteConfig/`
  MYPROFS=`echo "$INCLIST" | egrep "/${MYBASE}$|/${MYBASE}-"`
  [ ! -z "$MYPROFS" ] && MYSITE="`echo \"$MYPROFS\" | awk -F/ '{print $(NF-2)}' | sort -u`"
  NSITES=`echo $MYSITE | wc -w`
  if [ $NSITES -eq 0 ] ; then
    MYSITE=AnySite
  elif [ $NSITES -ne 1 ] ; then
    ShellMe "
      $0 $*:
	Parts of Jumpstart Profile exist in different Site directories:
      ===
	$MYPROFS
      ===
    "
  fi
  SITE=$MYSITE
  SITE_CONFIG_DIR=$INCDIR/$SITE/SiteConfig
  JS_SITE_CONFIG_DIR=$SITE_CONFIG_DIR

  JS_SITE_ENV_DIR=`dirname $JS_SITE_CONFIG_DIR`/Environment
  JS_HOST_ENV_FILE=$JS_SITE_ENV_DIR/$JS_MYNAME

  export INCDIR SITE SITE_CONFIG_DIR JS_SITE_CONFIG_DIR JS_SITE_ENV_DIR JS_HOST_ENV_FILE
}


GetSolVers() {

  #
  # Note: As of Solaris 10, cross-release Jumpstart support
  # is suspended, because Solaris-10 miniroot
  # fails to stage pre-solaris-10 machines.
  #
  # Support for this feature will be resumed as soon as
  # reasonable demand appears again
  #

  [ `echo $TARGET $TOSREL $BOOTED $BOSREL $TMINOR | wc -w`  -eq  5 ] && return 0
  #
  # get OSREL minus 3
  # (like 2.5.1 as opposed to 5.5.1) for booted and target OS
  #
  DEFSOL=2.9
  BOOTED=`expr \`uname -r | cut -d. -f-1\` - 3`.`uname -r | cut -d. -f2-`
  #
  # Try bootargs first
  #
  [ -z "$TARGET"   -a  -x /sbin/getbootargs ] && {
    for i in `/sbin/getbootargs 2>/dev/null` ; do
      echo $i | egrep -s '^[0-9][0-9\.]*$' && { TARGET=$i; break; }
    done
  }
  #
  # Now, check if /cdrom/.cdtoc has the same PRODVERS as $TARGET
  #
  [ -r /cdrom/.cdtoc ]  &&  . /cdrom/.cdtoc  && {
    [ "$PRODVERS" != "2.0"  -a  "$PRODVERS" != "$TARGET" -a  "2.$PRODVERS" != "$TARGET" ] && {
      WarnMe "
	    /cdrom/.cdtoc does not exist or contains wrong PRODVERS != TARGET
	    PRODVERS is $PRODVERS
	    TARGET   is $TARGET
	    Setting TARGET to $PRODVERS
      "
      TARGET=$PRODVERS
    }
  }
  #
  # See what SUNWcar pkginfo says
  #
  INFOFILE=/var/sadm/pkg/SUNWcar/pkginfo
  [ -r $INFOFILE ] && {
    TRYREL=`<$INFOFILE grep '^SUNW_PRODVERS=' | cut -d/ -f1 | cut -d= -f2`
    TRYTRG=""
    [ -n "$TRYREL" ] && TRYTRG=`expr \`echo $TRYREL | cut -d. -f-1\` - 3`.`echo $TRYREL | cut -d. -f2-`
    [ -n "$TARGET"  -a  "$TRYTRG" != "$TARGET" ] && ShellMe "TARGET $TRYTRG - mismatch with previously defined $TARGET"
    echo Setting TARGET to $TRYTRG as per SUNWcar/pkginfo
  }

  #
  # Failing that, assume target is the same as the booted jumpstart kernel
  #
  [ -z "$TARGET" ] && {
    WarnMe "Cannont determine the target version - setting to $TARGET"
    TARGET=$BOOTED
  }

  NotifyMe "Target Solaris version is $TARGET"
  [ -z "$TARGET" ] && ShellMe "Cannot figure out the targer OS version"
  #
  # Convert 2.x back to 5.x
  #
  MAJREL=`echo $TARGET | cut -d. -f-1`
  MINREL=`echo $TARGET | cut -d. -f2-`
  # TOSREL=`expr \`echo $TARGET | cut -d. -f-1\` + 3`.`echo $TARGET | cut -d. -f2-`
  [ x$MINREL != x ]  &&  TOSREL=5.$MINREL  || TOSREL=5.$MAJREL

  BOSREL=`expr \`echo $BOOTED | cut -d. -f-1\` + 3`.`echo $BOOTED | cut -d. -f2-`
  TMINOR=`echo $TOSREL | cut -d. -f2` ; [ "$TMINOR" -lt 7 ] && TMINOR=$TOSREL
  for i in TARGET TOSREL BOOTED BOSREL TMINOR; do eval echo $i=$`echo $i`; done
  export TARGET TOSREL BOOTED BOSREL TMINOR
}


SetSunClusterEnv() {
  #
  # We really prefere to set the SC_vars in the very beginning
  # of the whole custom Jumpstart finish scripts,
  # as some of these vars are referred to from many other
  # places apart from Scripts/Misc/add_SunCluster
  #
  SC_SITE_CONFIG_DIR=$SI_CONFIG_DIR/Profiles/$SITE/SiteConfig/SunCluster
  [ -d $SC_SITE_CONFIG_DIR/. ] || {
    echo "

	WARNING:

	       Sun Cluster will not be installed/configured on this node,
	       because site-specific cluster configuration directory
		 $SC_SITE_CONFIG_DIR
	       does not exist

    "
    return 0
  }

  SC_NODENAME=$SI_HOSTNAME
  SC_INST_CONFIG_DIR=`
    for f in \`find $SC_SITE_CONFIG_DIR -name Cluster_Wide\`; do
      . \$f
      echo \"\$SC_NODE_IDs\" | egrep -s $SC_NODENAME:[0-9] && echo \`dirname \$f\`
    done
  `

  [ `echo "$SC_INST_CONFIG_DIR" | wc -w` -ne 1 ] && {
    echo "

	WARNING:

	       Sun Cluster will not be installed/configured on this node,
	       because node-specific cluster configuration file
		 $SC_SITE_CONFIG_DIR/*/${SC_NODENAME}
	       does not exist or appears more than once

    "
    return 0
  }

  SC_INSTANCE=`basename $SC_INST_CONFIG_DIR`
  SC_ARGVAR_CLUSTERNAME=$SC_INSTANCE

  SC_PATH_TO_CD=$JS_MEDIA_DIR/Packages/SunCluster/3.1
  SC_AUTOINSTALL_DIR=$SC_PATH_TO_CD/java_es_05Q4_cluster/Solaris_sparc/Product/sun_cluster
  SC_AUTOINSTALL_TOOLSDIR="$SC_AUTOINSTALL_DIR/Solaris_$TMINOR/Tools"

  SC_SITE_CONFIG_FILE=$SC_SITE_CONFIG_DIR/Site_Wide
  SC_INST_CONFIG_FILE=$SI_CONFIG_DIR/Profiles/$SITE/SiteConfig/SunCluster/$SC_INSTANCE/Cluster_Wide
  SC_NODE_CONFIG_FILE=$SI_CONFIG_DIR/Profiles/$SITE/SiteConfig/SunCluster/$SC_INSTANCE/$SC_NODENAME

  SC_HOSTS_FILE=$SC_INST_CONFIG_DIR/etc/hosts

  # # # # # # # # # # # # # # #
  #
  # Source the more specific settings from
  # $SI_CONFIG_DIR/Profiles/$SITE/SiteConfig/
  #
  # export `set | awk -F= '/^SC_/ && !/^SC_AUTOINSTALL_D/ {print $1}'`
  for i in SC_SITE_CONFIG_FILE SC_INST_CONFIG_FILE SC_NODE_CONFIG_FILE; do
    f=`eval echo $\`echo $i\``
    echo Looking for $i=$f
    [ -f $f ] && . $f
  done

  [ x$SC_PRIMARY_NODE_NAME != x ] || StartShell "SC_PRIMARY_NODE_NAME not sourced from SC_INST_CONFIG_FILE ($SC_INST_CONFIG_FILE)"
  SC_PRIMARY_NODE_ADDR=`awk '$0~/^[1-9][1-9.]*.*'$SC_PRIMARY_NODE_NAME'/ {print $1}' $SC_HOSTS_FILE | head -1`
  [ x$SC_PRIMARY_NODE_ADDR != x ] || StartShell "Could not resolve $SC_PRIMARY_NODE_NAME via $SC_HOSTS_FILE"

  #
  # Exporting all SC_variables is a bit dangerous here, as they may start conflictig with some
  # read-only ksh variables determined by Sun's "scinstall" script triggered from $SC_CONFIG_LINE
  # in add_SunCluster script. If such thing happens, grep out the conflicting variable here,
  # like it's done for SC_AUTOINSTALL_D* variables below
  #
  export `set | grep = | awk -F= '/^SC_/ && !/^SC_AUTOINSTALL_D/ && !/^SC_Append_Hosts/ {print $1}'`
}


SC_Append_Hosts() {
  #
  # Add to /etc/hosts Sun Cluster hosts entries that aren't there yet
  # The necessary data will be found in "hosts" file within SC_INST_CONFIG_DIR tree
  #
  [ -f $SC_HOSTS_FILE ] || StartShell "No SC_HOSTS_FILE $SC_HOSTS_FILE"
  for i in `awk '$1~/^[1-9][0-9.]*$/ {print $2}' $SC_HOSTS_FILE`; do
    awk '$1~/^[1-9][0-9.]*$/' $ROOT/etc/hosts | expand | egrep -s " $i | $i$" || awk '$1~/^[1-9][0-9.]*$/ && $2=="'$i'" {print}' $SC_HOSTS_FILE >>$ROOT/etc/hosts
  done
}


MountJSMedia() {
  #
  # We presume that $JS_MEDIA_DIR can be mounted the same way as
  # /cdrom is mounted, except we must consider 2 variants -
  # Jumpstart/media/CDs/2.X and just /Jumpstart/media
  #
  # In the former case, do nothing.
  #
  # Remember, we need to handle local install media (CDs and HDs) as well
  #
  [ -d $JS_MEDIA_DIR/Packages/. ]  || {
    [ -d $JS_MEDIA_DIR/. ]           || mkdir -p $JS_MEDIA_DIR
    JS_MEDIA_DEV=`cd $SI_CONFIG_DIR && df -ka . | awk '$NF~/\// {print $1}' | sed 's:/config:/media:'`
    mount $JS_MEDIA_DEV $JS_MEDIA_DIR || ShellMe "
       Failed to
	  mount $JS_MEDIA_DEV $JS_MEDIA_DIR
    "
  }

  [ -d /cdrom/Solaris_$TMINOR/Product/. ] || {
    ShellMe "
      Multi-version media handling is under construction again

    "
  }
}


AddInstallUser() {
  #
  # Sometimes, patchadd/fastpatch checkinstall fail
  # too strict access permissions on patch directory structure.
  #
  # if install user exists, patchadd will be run as "install",
  # instead of "nobody"
  #
  # This user will be removed by SecClean script called from Finish/Std
  #
  egrep -s '^install:' $ROOT/etc/passwd && egrep -s '^install:' $ROOT/etc/shadow && return 0
  echo "install:x:0:1:Install-User:/:/bin/false" >>$ROOT/etc/passwd
  echo "install:NP:6445::::::"                    >>$ROOT/etc/shadow
}


FindFreeDisk() {
  #
  # Find the largest unused disk (DID would be better, but we need a reboot for this)
  #
  echo | format | awk '$2~/c[0-9][0-9]*t[0-9A-F]/ {print $2}' | sort -u >/tmp/AllDisks

  FreeDisks=`
    (
      metastat | awk '{print $1}'
      df -ka   | awk '{print $1}' | awk -F/ '{print $NF}'
    ) | grep 'c[0-9][0-9]*t[0-9A-F]' | sed 's/s[0-9]$//' | sort -u | diff /tmp/AllDisks - | awk '$1=="<" {print $2}'
  `

  [ `echo $FreeDisks | wc -l` -lt 1 ] && StartShell "No unused disks found to allocate the shared storage"

  LargestDiskSize=0
  LargestDiskName=`echo $FreeDisks | awk '{print $1}'`
  for d in $FreeDisks; do
    DiskSize=`prtvtoc -h /dev/rdsk/${d}s2 | awk '$5~/^[0-9][0-9]*$/ {print $5}' | sort -n | tail -1`
    [ $DiskSize -le $LargestDiskSize ] && continue
    LargestDiskSize=$DiskSize
    LargestDiskName=$d
  done
}


SetJVars() {
  #
  # Set Jumpstart variables
  # for use by other Begin/Finish/Postinstall scripts
  #

  VarsAreSet=Yes ; export VarsAreSet

  MakePath
  SetRootOpts
  GetSolVers
  FindRootDisk
  FindNetInfo
  FindSiteName
  SetSunClusterEnv
  MountJSMedia

}

# ==== Don't add anything below this line =====
SubrIsRead=Yes

