#!/bin/sh
#
# load_pkgs [ -pkg ] infofl [tapedev]
#
#       -pkg: if turn this on, infofl is pkginfo format, or it should
#             be the file format with sorted package field like:
#		pkgname pdtname pdtsize platform FMrelease	
#
#	This program attempts to load the packages listed in infofl from
#	tapedev.  If no tapedev pass in, It will pop up menu to ask user
#	all the media device information based on history file (.cdsloadrc)
#	and mediaMap.<OS> file.
#
#	This involves executing each package's script (PRE_LOAD)
#	and foreach script that exit'ed with zero status, unload the 
#	appropriate pieces of the tape and re-execute the script (POST_LOAD).
#
#Hariraj: changed the prod_flag to skipcd_flag
#############################################################################
#############################################################################
#
#	Copyright (C) Cadence Design Systems, Inc. All rights
#	reserved.  Unpublished -- rights reserved under the
#	copyright laws of the United States of America.
#
#			RESTRICTED RIGHTS LEGEND
#	Use, duplication, or disclosure by the Government is subject
#	to restrictions as set forth in subparagraph (c)(l)(ii) of 
#	the Rights in Technical Data and Computer Software clause 
#	at DFARS 52.227-7013.
#
#			Cadence Design Systems, Inc.
#			555 River Oaks Parkway
#			San Jose, CA 95134	USA
#
#############################################################################
BOURNE=/bin/sh
XTERMPATH=/usr/bin/X11
XTERMBIN=xterm
XTERMOPTS="-T 'SoftLoad 6.0 Console' -fn 9x15  -sl 200 -g 80x40+0+0 -bg \#e0e0e0 -fg \#800000 -sb -e ${BOURNE} softload_GUI"
sysPATH=/bin:/usr/bin:/usr/ucb:$XTERMPATH

jsr=''

Clear() {
    clear		2>/dev/null	#beware of bad termcap entry
}

Page() {
    TERM=vt100 MORE=""  more		#make sure we don't clear screen
}

EchoN() {
    echo  "$*\c"
}

Beep() {
    tput bel		2>/dev/null
}


OSvendor=ibmrs
OSarchs=$OSvendor
Archtype() {
    echo $OSvendor
}

Exit() {

    status=$1; shift
    files="$*"
    for file in $files; do
        test -f $file && rm $file
    done
    exit $status

}

Affirmative() {
    while : ; do
	read Affirm
	case $Affirm in
	    [yY]*) return 0 ;;
	    [nN]*) return 1 ;;
	    *)     $jsr EchoN "Please press y (yes) or n (no) : " ;;
	esac
    done
}

Proceed() {
    test "X$1" = 'X-q' || $jsr EchoN "Press [Return] to proceed, q to quit : "
    while : ; do
	read proc < /dev/tty
	case $proc in
	    "")    return 0 ;;
	    [qQ]*) return 1 ;;
	    *) 	   $jsr EchoN "Press [Return] to proceed, q to quit : " ;;
	esac
    done
}


SetExport() {
    file=$1
    variable=$2
    entry=$3

    test -f $file || touch $file
    grep -s ${variable} ${file} 2>&1 > /dev/null

    if [  "$?" = 0 ]; then
        grep -v ${variable} ${file} > /tmp/infile$$
        cp /tmp/infile$$ ${file}
        rm /tmp/infile$$
    fi

    echo "${variable}=\"${entry}\" ; export ${variable}" >> $file
}

#This did not work for the -v flag. Fixed it so that it works fine
#now



Fgrepf() {		# fgrep -v filename
    vset=false
    Util="fgrep"
    opts=
    while test $# -gt 0 ; do
       case $1 in
          -egrep)
               Util="egrep"
               shift;;
          -v)
               opts="$opts `expr X$1 : '.\(.*\)'`"
               shift
               vset=true;;
          -*)
               opts="$opts `expr X$1 : '.\(.*\)'`"
               shift;;
           *)  break;;
       esac
    done

    patFl=$1
    srcFl=$2

    split -25 $patFl /tmp/split$$_

    for pat in /tmp/split$$_* ; do
      if $vset; then
       count=0
       $Util $opts -f $pat $srcFl > /tmp/srcTFL$$
       srcTFL="/tmp/srcTFL$$"
       for pat1 in /tmp/split$$_* ; do
        count=`expr $count + 1`
        $Util $opts -f $pat1 $srcTFL > /tmp/srcFL${count}$$
        srcTFL="/tmp/srcFL${count}$$"
        echo $count > /tmp/count$$
       done
       if [ -s /tmp/count$$ ]; then
        read count < /tmp/count$$
       fi  
       cat /tmp/srcFL${count}$$ | sort -n | uniq >> /tmp/resFL$$
       while [ "$count" -gt 0 ]; do
         rm -f /tmp/srcFL${count}$$
         count=`expr $count - 1`
       done
       rm -f /tmp/srcTFL$$
      else
        $Util $opts -f $pat $srcFl
      fi
    done | sort -n | uniq
    if $vset; then
      cat /tmp/resFL$$ | sort -u | sort -n | uniq
    fi
    rm -f /tmp/resFL$$ /tmp/count$$ /tmp/split$$_* 
    
}

LoginName() {	# who'd you log in as
    who am i | sed -e 's/[ 	].*//' -e 's/.*\!//'
}

UserName() {
    whoami
}






Intr_Clean () {
   echo "${NL}Cleaning up...${NL}"
   rm -f ${tmp_dir}/ctl_files_xtract*
   rm -f ${tmp_dir}/tmpfl*
   rm -f ${tmp_dir}/awk* ${tmp_dir}/dels* ${tmp_dir}/load* ${tmp_dir}/pkginfo.ld*
   rm -f ${tmp_dir}/totalSize* ${tmp_dir}/mediaLoc*
   rm -f /tmp/df*
}

test -z "$Rm" && Rm=/bin/rm -f;		export Rm
if [ -z "$Proot" ]; then  
    $jsr EchoN "${NL}$0 environment not initialized. ${NL} $0 Can only be used when called from SoftLoad." 				1>&2
    exit 1 
fi
export Proot

trmdev=/dev/tty
which stty >> /dev/null
if [ ! "$status" -a "`stty -g`" = "" ] ; then
    trmdev=/dev/null
fi

if [ -z "$InstPlat" ]; then
  $jsr EchoN "${NL}$0 Installation platform not specified ${NL}" 1>&2
  exit 1
fi
export InstPlat

#This will be used to list products in the pdts directory
if [ "X$InstPlat" = "Xsun4" -o "XInstPlat" = "Xsun" ]; then #{
  tplat="sun4_"
else
  tplat=$InstPlat
fi #}

useGUI=${useGUI?'useGUI environment not initialized'}

if [ "X$1" = "X-pkg" ]; then #{
  pkgflag=$1
  shift
fi  #}

info=$1 ; shift
mediaSpecified=
test $# -gt 0 && {
  inputDev=$1
  mediaSpecified="true"
}

tmp=$Proot/install/tmp
pkgs=$Proot/install/pkgs
history=$Proot/install/tmp/install.history
bundles=$tmp/bundles.${InstPlat}
mapinfo=$tmp/mapinfo.${InstPlat}
pkginfo=$tmp/pkginfo.${InstPlat}
recordFile=$Proot/install/.cdsloadrc.${OSvendor}
sizefl=$tmp/totalSize$$
selprodfile=$tmp/selprodfile
okunk=$tmp/okunk$$


ARCHTYPE=`$jsr Archtype`; export ARCHTYPE  #may be utilized by exe
TIMESTAMP=`date`;  export TIMESTAMP  #may be utilized by exe

loadLog=/tmp/load.msg
cnt=1; 
while [ -f $loadLog$cnt ]; do  #{
  cnt=`expr $cnt + 1`;  
done  #}
$Rm $loadLog
ln -s load.msg$cnt $loadLog || {
    echo "Warning: logfile saved to $loadLog$cnt"			1>&2
}
loadLog=$loadLog$cnt;		export loadLog

echo "$TIMESTAMP" > $loadLog

loads=$tmp/loads$$
> $loads


if [ -z "$bin_dir" ]; then  #{
  bin_dir=`pwd`; export bin_dir
fi  #}

tmp_dir=$bin_dir/../tmp
cd $Proot

addSize=0
totalSize=0

NL="
"

#This is for specifying the configure menu to be the default


defaultConfigOpt=0;


#Format of the $info or $tmpfl (if the -pkg flag is not set)
#The pkg flag is set if only -pkg option is used with the name
#of packages to be installed on the command line. It is not set
#if just the -pkg option is used
#deskVhdlDocC02.20-p005 22650 sun4 9502
#pkgname pdtname platform release

#If the -pkg flag is set then the format of the $info file is:
#synSmart~~~02.30~sun4~ synSmart02.30-p005sun4 14511 9504S2P1_CD 4 16
#Pkgdesc pkgname pkgsize MEDIALabel MediaNum FSNum


#If we are using the default install option
#let the customer what all products are being installed

#NoConfirm set to yes we are using the command line interface

if [ "X$default_install" = "Xyes"  -o "X$NoConfirm" = "Xyes" ]; then
  if [ -s $selprodfile ]; then #{
    sort -u +2 -3 $selprodfile  > $tmp/prodlst_$$
    $jsr EchoN "${NL}The following products will be installed or updated: ${NL}"
    $bin_dir/process_file 4 p $Proot i $tmp/prodlst_$$ F "~"
    $jsr EchoN "${NL}"
  else
    $jsr EchoN "${NL}Warning: File $selprodfile not found. ${NL}Could not list the products being installed.${NL}"
  fi  #}
  rm -f $tmp/prodlst_$$ 
fi


#We now check for any unselected products and probelms with updating it.
#Get the names of products with ok files (for the InstPlat)

#Now for the history stuff. We add the information about the current
#install into the history file.

if [ ! -f $history ]; then
  >$history
fi

mediaMap=$Proot/install/tmp/mediaMap.$InstPlat

{
  echo "=====================================================" 
  user=`$jsr UserName`
  mc=`uname -n`
  day=`date +%m/%d/%y`
  time=`date +%H:%M:%S`

  if [ -s "$pkginfo" ]; then
    msId=
    medias=`awk '{ print $4 }' $pkginfo | sort -u` 
    for med in $medias; do
      msId="$msId $med"
    done
  fi

  echo "${user}@${mc} installing from media $msId, on $day at ${time}"

  if [ -z "$pkgflag" ]; then
    if [ -s $selprodfile ]; then
      echo "Products selected for Installation:" 
      awk '{print $3 " " $5 " " $6 }' $selprodfile | sort -u
    else
      echo "Could not determine products selected for installation"
    fi
  else
    if [ -s $info ]; then
      echo "Packages selected for Installation:" 
      awk '{print $2}' $info | sort -u
    fi
  fi
  echo "--------------------------------"
  #After this check_pdtok will add lines to the
  #logfile as soon as a product is installed
} >> $history


#Now we delete the packages that have oder version installed.
#This was being done in load_fltr earlier.
# what packages should be deleted prior to loading selected packages?

#Change to bin_dir to do all this stuff
cd $bin_dir

echo " "

deleteData=$Proot/install/tmp/mapinfo.$InstPlat
if [ -s $deleteData ]; then  #{
  tmpExprs=$tmp/pkgExpr$$
#
# generate and run awk program with lines of the following form
# to collect expressions for pkgs which may need to be deleted
#   $1 == "pkgname" { print $2; next }
#
  if [ ! -z "$pkgflag" ]; then #{
    sed  's@^[^ ]* \([^ ]*\).*$@$1 == "\1" { print $2; next}@' $info \
	    >  $tmp/awke$$
  else
    sed  's@\([^ ]*\).*$@$1 == "\1" { print $2; next}@' $info \
    >  $tmp/awke$$
  fi  #}
  awk -f $tmp/awke$$  $deleteData > $tmpExprs
  $Rm    $tmp/awke$$

  if [ -s $tmpExprs ]; then  #{
    tmpDels=$tmp/dels$$
    $BOURNE $bin_dir/delete_fltr -pkg -quite -M "
The following packages should be deleted before new versions are installed.
Confirm the packages to be deleted:" $tmpDels +$tmpExprs

    if [ -s $tmpDels ]; then  #{
      $jsr EchoN "Deleting earlier versions of packages.. ${NL}${NL}"
      $BOURNE $bin_dir/delete_pkgs $tmpDels || Exit $? $tmpDels $tmpExprs
    fi  #}
    test -s $tmpDels && $Rm $tmpDels
    echo ""
  fi  #}
  $Rm $tmpExprs
fi #}

#Back to Proot

cd $Proot


################################################################
# Extract exe and inv files for selected packages
################################################################

if [ -s $ctl_files_xtract ]; then   #{

  openMedia="$BOURNE  $bin_dir/media_iface $$  open"
  readMedia="$BOURNE  $bin_dir/media_iface $$  xtract"
  closeMedia="$BOURNE $bin_dir/media_iface $$ close"
  skipcd_flag=noskip
  prod_flag=prodinfo

  #mounted_tapeset is exported from softload & softload_gui
  
  grep "${mountedCD}:1" < $mediaMap > /tmp/media$$

  read mediaID media_type therest < /tmp/media$$
  mediaSet=`echo $mediaID | sed 's/:.*//g'`
  mediaNum=`echo $mediaID | sed 's/.*://g'`
  mediaTxt=`echo $therest | tr "~" " "`
  $Rm /tmp/media$$
  

  #the line below is by hariraj to fix a bug. Even though .cdsloadrc
  #was modified but it was not run so that the environment variables
  #DeviceCD and DeviceTape had the previous value. Then media_cntrl
  #would try to read the mount point specified previously

  if [  -z "$mediaSpecified" ]; then  #{
    test -s $recordFile && . $recordFile
    case $media_type in  #{
      CDROM)   device=$DeviceCD;;
      TAPE)    device=$DeviceTAPE;;
    esac  #}
  else
    device=$inputDev
  fi  #}

  echo "Checking for $mediaTxt ......... " 
  while : ; do   #{
    $openMedia $device $mediaSet $mediaNum $media_type $skipcd_flag $prod_flag
    case $? in  #{
      0) 
        break;;
      10)  #ASCII Interface returns
        while : ; do  #{
          $BOURNE $bin_dir/getInstMedia $media_type $device <$trmdev
          case $?  in  #{
            0) break ;;
            1) echo "${NL}The specified $media_type device cannot be used."
                $jsr EchoN "Re-specify the device? [y/n]"
                $jsr Affirmative < $trmdev || break ;; # try again, or fail
 
            255) exit 0 ;;
            *) exit $? ;;
          esac  #}
        done   #}
        test -s $recordFile && . $recordFile
        case $media_type in  #{
          TAPE)   device="$DeviceTAPE" ;;
          CDROM)  device="$DeviceCD" ;;
        esac  #}
        ;;
      15) #GUI part of media_iface returns if CDROM mount 
          #point has changed.
        while : ; do  #{
          . $tmp_dir/mediaLoc
          case $media_type in #{
            TAPE)   device="$DeviceTAPE" 
              variable="DeviceTAPE" ;;
            CDROM)  device="$DeviceCD" 
              variable="DeviceCD" ;;
          esac  #}

          if $BOURNE $bin_dir/media_iface $$ open $device < $trmdev; then #{
            SetExport $recordFile ${variable} $device
            rm -f $tmp_dir/mediaLoc
            break
          else
            $BOURNE $bin_dir/toplevel.sh 14 $media_type $device > $tmp_dir/mediaLoc || \
            Exit $?  $tmp_dir/mediaLoc 
            case $? in  #{
              250) exit 250;;
              255) exit 255;;
              *) ;;
            esac  #} 
          fi  #}
        done  #}
        test -s $recordFile && . $recordFile
        case $media_type in  #{
          TAPE)   device="$DeviceTAPE" ;;
          CDROM)  device="$DeviceCD" ;;
        esac  #}
        ;;
      *) Exit $? ;;
    esac  #}
  done  #}

  echo "${NL}Extracting control programs ......... " 
  split -100 $ctl_files_xtract $tmp/ctl_files_split$$_
  for each_split in $tmp/ctl_files_split$$_*; do
      $readMedia 1 `cat $each_split` || exit 1
      $closeMedia || exit 1
      $openMedia $device $mediaSet $mediaNum $skipcd_flag $prod_flag || exit 1
  done
  $Rm  $tmp/ctl_files_split$$_* 
  $closeMedia || exit 1
fi  #}




# verify that data files exist for selections

#This section will generate the nok file for the product and
#Add the product name to the ok file for the pkg.nok file or the 
#pkg.ok file.

tmpfl=$tmp/tmpfl_$$
if [ -z "$pkgflag" ]; then  #{

  $jsr EchoN "${NL}Updating package installation information."

  #Instead of using the info file we will use the selprodfile 
  #if it exists else we use the info file

  if [ -s $selprodfile ]; then #{
    cat $selprodfile > $tmpfl
  else
    $jsr EchoN "${NL}Warning: File with the list of selected products does not exist.${NL}Updating product statuses based on the packages being loaded.${NL}Some products might end up with a failed status.${NL}Just select those products for installation once again and product statuses will be updated.${NL}"
    sed  's@^[^ ]* \([^ ]*\).*$@$3 == "\1" { print }@' $info | sort -u > $tmp/awklp$$
    awk -f $tmp/awklp$$ $bundles > $tmpfl1
    $Rm $tmp/awklp$$
  fi #}
    while read pdtdesc pkgname pdtname pdtsize platform FMrelease ; do  #{
      pdtRoot="$Proot/install/pdts/${pdtname}_${platform}_${FMrelease}"
      pkgRoot="$Proot/install/pkgs/${pkgname}"
      #Get the regular expression of this package name from the
      #mapinfo file
      pkgexpr=`grep "^${pkgname} " $mapinfo | awk '{print $2 }' | sed 's@[\^\$]@@g'`
      test -s ${pkgRoot}.ok && {
      # If the pkgname.ok file exists (it's already been loaded
      # successfully) and this product isn't listed as depending
      # on that package, establish that relationship
      test `egrep -c "^$pdtname $platform " ${pkgRoot}.ok` -eq 0 && \
        echo $pdtname $platform $FMrelease >> ${pkgRoot}.ok
      }
      #If the product.ok file exists and this package doesn't
      #appear in it move it to product.nok and add the package to it.
      test -s ${pdtRoot}.ok && {
        if [ "X$pkgexpr" = "X" ]; then #{
          cat ${pdtRoot}.ok > ${pdtRoot}.tmp
        else
          egrep -e "^${pkgexpr}$" -v ${pdtRoot}.ok > ${pdtRoot}.tmp
        fi #}
        test `egrep -c "^$pkgname" ${pdtRoot}.tmp` -eq 0 && \
        echo $pkgname >> ${pdtRoot}.tmp
        /bin/cat ${pdtRoot}.tmp > ${pdtRoot}.nok
        $Rm ${pdtRoot}.tmp ${pdtRoot}.ok
      }     
      # If the product.nok file doesn't exist, create it and add the
      # initialization info
      test -s ${pdtRoot}.nok || {
        echo "$pdtdesc pkgname $pdtname $pdtsize $platform $FMrelease" > ${pdtRoot}.nok
        # New product.nok generated - output a dot to let them know
        # we're still here and running
        $jsr EchoN "."
      }
      # Update processing files to reflect the products/packages to
      # load
      # If this package doesn't yet appear in the product.nok file,
      # add it in
      test -s ${pdtRoot}.nok && {
        if [ "X$pkgexpr" = "X" ]; then
          cat ${pdtRoot}.nok > ${pdtRoot}.tmp
        else
          egrep -e "^${pkgexpr}$" -v ${pdtRoot}.nok > ${pdtRoot}.tmp
        fi
        test `egrep -c "^$pkgname" ${pdtRoot}.tmp` -eq 0 && \
        echo $pkgname >> ${pdtRoot}.tmp
        /bin/cat ${pdtRoot}.tmp > ${pdtRoot}.nok
        $Rm ${pdtRoot}.tmp 
      }
    $jsr EchoN "."
    done  < $tmpfl #}
fi  #}

$Rm $tmpfl

echo " "

$jsr EchoN "${NL}Checking data files...${NL}"

#Read the tmpfl, for all the pkgs that have the .exe and .inv files
#move those files to the pkgs directory and put the pkgname into
#the info file ($info is regenerated)

/bin/cat $info > $tmpfl
if [ ! -z "$pkgflag" ]; then  #{
  cat $tmpfl | 
    while read pkgdesc pkgname remainder; do  #{
      #relocate applicable package files from tmp area
      mv $tmp/$pkgname.exe $tmp/$pkgname.inv $pkgs 2> /dev/null
      test -s $tmp/$pkgname.att && mv $tmp/$pkgname.att $pkgs
      if [ -f $pkgs/$pkgname.inv -a -f $pkgs/$pkgname.exe  ]; then  #{
        echo $pkgdesc $pkgname "$remainder" 
      else         
        echo "SL-9: Could not locate data files for $pkgname (exe,inv)" 1>&2 
     fi  #} 
  done > $info   #} 
else
  cat $tmpfl | 
  while read pkgname remainder; do  #{
    # relocate applicable package files from tmp area
    mv $tmp/$pkgname.exe $tmp/$pkgname.inv $pkgs 2> /dev/null
    test -s $tmp/$pkgname.att && mv $tmp/$pkgname.att $pkgs
    if [ -f $pkgs/$pkgname.inv  -a -f $pkgs/$pkgname.exe ]; then  #{
	    echo "$pkgname $remainder" 
    else         
      echo "SL-9: Could not locate data files for $pkgname (exe,inv)" 1>&2 
    fi  #}         
  done > $info   #} 
fi  #}

$Rm $tmpfl 

# Run exe's (PRE_LOAD)

$jsr EchoN "${NL}Executing control programs (pre-load) ...${NL}"


phase=PRE_LOAD;  export phase
if [ ! -z "$pkgflag" ]; then  #{
  while read pkgdesc pkgname remainder ; do  #{
    pkgRoot=./install/pkgs/$pkgname
    test -f $pkgRoot.ok && $Rm $pkgRoot.ok	# reloading a package

    echo "$pkgdesc $pkgname $remainder" > $pkgRoot.nok
    if [ -s $pkgRoot.exe ]; then   #{run exe
      echo "Executing $pkgname control program ($phase)"  >> $loadLog
      if PKGNAME=$pkgname $pkgRoot.exe < $trmdev; then  #{
        echo "$pkgname control program ($phase) successful" >> $loadLog
      else
        $jsr EchoN " ${NL}SL-10:Installation of $pkgname declined by control program ($phase) ${NL}$pkgname will not be installed" | tee -a $loadLog 1>&2
        continue
      fi  #}
    fi  #}
    echo "$pkgdesc $pkgname $remainder" >> $loads
  done < $info  #}
else
  while read pkgname pdtname platform FMrelease ; do  #{
    pdtRoot=./install/pdts/${pdtname}_${platform}_${FMrelease}
    pkgRoot=./install/pkgs/$pkgname
    test -f $pdtRoot.ok && $Rm $pdtRoot.ok   # reloading a product

    # this should not happen, since we have parse to get the 
    #packages which can be installed	
    test -f $pkgRoot.ok && $Rm $pkgRoot.ok	    

    pkgline=`awk '$2 == "'$pkgname'" { print }' $pkginfo`

    echo $pkgline > $pkgRoot.nok
    if [ -s $pkgRoot.exe ]; then  #{run exe
      echo "Executing $pkgname control program ($phase)"  >> $loadLog
      if PKGNAME=$pkgname $pkgRoot.exe < $trmdev; then  #{
        echo "$pkgname control program ($phase) successful" >> $loadLog
      else
        $jsr EchoN "${NL}SL-10:Installation of $pkgname declined by control program ($phase) ${NL}$pkgname will not be installed" | tee -a $loadLog       1>&2
        continue
      fi  #}
    fi  #}
    echo $pkgline	>> $loads
  done < $info  #}
fi  #}

#Format of the loads file (Same whether -pkg flag is set or not set)
#synLibDocR~~~~~~~~~~~~~~~02.20 synLibDocR02.20-p002 672 Test_SUN4 3 1
#pkgdesc pkgname pkgsize tapeset tapenum fsnum

if [ ! -s $loads ]; then		#empty load file...done
    $Rm $loads
    exit 0
else
    /bin/cat $loads > /tmp/loads$$
    sort -u /tmp/loads$$ > $loads
    $Rm /tmp/loads$$
fi

#We Now do the disk checks
#If they had been postponed

if [ -s $tmp/mdsk_chk ]; then
  $Rm $tmp/mdsk_chk
  $BOURNE $bin_dir/disk_chk -T "product" $loads
  dcstatus=$?
  case $dcstatus in #{
  0 ) ;; #Proceed with instllation
  * ) Exit 250 $loads ;;
  esac #}
fi
  
# break each pkginfo line into one line for each referenced fileset 

cat $loads | sort -u |
while read pkgdesc pkgname pkgsize pkgtapeset tapeinfo ; do
    awkcommand='BEGIN{ FS="	" } 
{for( i=1; i<=NF; i++ ) print "'$pkgname'", "'$pkgsize'", "'$pkgtapeset'", $i}'
    echo "$tapeinfo" | awk "$awkcommand" 
done | 		#line: pkgname pkgsize tapeset tapenum fsnum [files]

# sort pkginfo lines by tapeset, tapenum, fileset 

sort -n +3 +4 > $tmp/pkginfo.ld$$ 		#sort by tapenum,fileset

$Rm $loads

#
#Format of  pkginfo.ld.. file 
#synTI02.20-s026sun4 1831 Test_SUN4 3 2
#pkgname pkgsize tapeset tapenum fsnum
#
#load from tapeset with lowest tapenum first
#Here we use the exported variable once again.
Tapesets=$mountedCD
tapenum=`awk 'NR == 1 {print $4}' $tmp/pkginfo.ld$$`
tapeID="${Tapesets}:${tapenum}"
tapesets="$Tapesets "`awk '$3 != "'$Tapesets'"{print $3}' $tmp/pkginfo.ld$$ | sort -u`

mediaMap=$Proot/install/tmp/mediaMap.$InstPlat

for tapeset in $tapesets; do  #{sort by tapeset,tapenum,fileset
  awk '$3 == "'$tapeset'"' $tmp/pkginfo.ld$$
done > $tmp/pkginfo.lD$$  #}

mv $tmp/pkginfo.lD$$ $tmp/pkginfo.ld$$
totalSize=`awk '{ dktotal += $2 } END { printf "%d\n", dktotal }' $tmp/pkginfo.ld$$`
echo $totalSize > $sizefl

# foreach {tapeset,tapenum,fileset} triplet 
#    print a single line showing size and packages affected
#    print a single line of the format: tapeset tapenum fsnum [files]

cat $tmp/pkginfo.ld$$ |
{
  pkgnames=
  fsSize=
  formerTset=
  formerTnum=
  formerFset=
  fsFiles=
  while read pkgname pkgsize tapeset tapenum fileset files; do  #{
    if [ "$tapeset" = "$formerTset" -a "$tapenum" = "$formerTnum" -a \
          "$fileset" = "$formerFset" ]; then  #{
      pkgnames="$pkgnames $pkgname"
      fsSize=`expr $fsSize + $pkgsize`
      fsFiles="$fsFiles $files"
    else   #output lines, reset variables
      if [ ! -z "$pkgnames" ]; then #{not first iteration
        echo $fsSize $pkgnames
        echo $formerTset $formerTnum $formerFset $fsFiles
      fi  #}
      pkgnames=$pkgname
      fsSize=$pkgsize
      formerTset=$tapeset
      formerTnum=$tapenum
      formerFset=$fileset
      fsFiles=$files
    fi  #}
  done  #}
  echo $fsSize $pkgnames
  echo $formerTset $formerTnum $formerFset $fsFiles
} |

# Now actually do the loading, running the "exe" (POST_LOAD) after 
#reading  all filesets associated with a package. 

{
  open_tape="$BOURNE $bin_dir/media_iface 	$$ open"
  read_tape="$BOURNE $bin_dir/media_iface 	$$ xtract"
  close_tape="$BOURNE $bin_dir/media_iface	$$ close"

  skipTape=""	  #no skip specified, yet
  totalSize=`cat $sizefl`
  while read fsSize pkgnames ; do  #{
    read tapeset tapenum fileset files
    addSize=`expr $addSize + $fsSize`
    $BOURNE $bin_dir/read_media $tapeset:$tapenum $mediaMap < $trmdev > /tmp/media$$
    . /tmp/media$$
    $Rm /tmp/media$$
    mediaTxt=`echo $mediaTxt | tr '~' ' '`
    if [ -z "$mediaSpecified" ]; then  #{
      test -s $recordFile && . $recordFile
      case $mediaType in  #{
        TAPE)   tapedev="$DeviceTAPE" ;;
        CDROM)  tapedev="$DeviceCD" ;;
        TFILE)  tapedev="$Proot/install" ;;
      esac  #}
    else
      if [ "$mediaType" = "TFILE" ]; then  #{
        tapedev="$Proot/install"
      else
        tapedev="$inputDev"
      fi  #}
    fi  #}
    if [ "$tapeset:$tapenum" = "$skipTape" ]; then  #{go to next tape
      echo "SKIPTAPE $skipTape $pkgnames"  >> $loadLog
      echo "Skipping $pkgnames" 
      continue
    fi  #}

    if [ "$tapeset:$tapenum" != "$lastTRead" ]; then  #{get right tape
      test ! -z "$lastTRead" && {
        $close_tape <$trmdev #close old
        Beep
      }
      echo "${NL}Checking $mediaTxt ..."	
      #Changes to implement the mount point change

      cont_flag=""

      while : ; do   #{
        $open_tape $tapedev $tapeset $tapenum $mediaType <$trmdev	#open new
        case $? in  #{
          0) lastTRead="$tapeset:$tapenum"
            break;;
          5) skipTape="$tapeset:$tapenum"
            echo "SKIPTAPE $skipTape $pkgnames"  >> $loadLog
            echo "Skipping $pkgnames"
            cont_flag="yes"
            break;;
          10)
            while : ; do  #{
              $BOURNE $bin_dir/getInstMedia $mediaType $tapedev <$trmdev
              case $?  in  #{
                0) break ;;
                1) echo "${NL}The specified $mediaType device cannot be used."
                    $jsr EchoN "Re-specify the device? [y/n]"
                    $jsr Affirmative < $trmdev || break ;; # try again, or fail
 
                255) exit 0 ;;
                *) exit $? ;;
              esac  #}
            done   #}
            test -s $recordFile && . $recordFile
            case $mediaType in  #{
              TAPE)   tapedev="$DeviceTAPE" ;;
              CDROM)  tapedev="$DeviceCD" ;;
              TFILE)  tapedev="$Proot/install" ;;
            esac  #}
            ;;
          15) #GUI part of media_iface returns if CDROM mount 
              #point has changed.
            while : ; do  #{
              . $tmp_dir/mediaLoc
              case $mediaType in  #{
                TAPE) device="$DeviceTAPE"
                  variable="DeviceTAPE" ;;
                CDROM) tapedev="$DeviceCD"
                  variable="DeviceCD" ;;
              esac  #}
              if $BOURNE $bin_dir/media_iface $$ open $tapedev < $trmdev; then #{
                SetExport $recordFile ${variable} $tapedev
                rm -f $tmp_dir/mediaLoc
                break
              else
                $BOURNE $bin_dir/toplevel.sh 14 $mediaType $tapedev > $tmp_dir/mediaLoc || \
                Exit $?  $tmp_dir/mediaLoc 
                case $? in  #{
                  250) exit 250;;
                  255) exit 255;;
                  *) ;;
                esac  #} 
              fi  #}
            done  #}
            test -s $recordFile && . $recordFile
            case $mediaType in  #{
              TAPE)   tapedev="$DeviceTAPE" ;;
              CDROM)  tapedev="$DeviceCD" ;;
              TFILE)  tapedev="$Proot/install" ;;
            esac  #}
            ;;
          *) Exit $? $sizefl ;;
        esac  #}
      done  #}
      test -z "$cont_flag" || continue
    fi  #}

    for pkgname in $pkgnames; do  #{
      echo "$pkgname $tapeset $tapenum $fileset" >> ./install/pkgs/$pkgname.nok
    done  #}

    # approximate 1 dot for every 2.5% of fileset read
    dotInterval=`expr $fsSize / 40 \| 1`
	    
    # do the tape commands

    echo "${NL}Tape: $tapeset:$tapenum Fileset: $fileset Affecting: $pkgnames" >> $loadLog 
    $jsr EchoN "${NL}loading $pkgnames "

    if [ "X$tapenum" != "X" ]; then  #{
      $read_tape -v $dotInterval "$fileset" "$files" <$trmdev || {
        echo "${NL}SL-11: Error loading software ...
Refer to $loadLog for load log"		| tee -a $loadLog 1>&2
        $close_tape <$trmdev
        $BOURNE $bin_dir/delete_fls $pkgnames
        Exit 1 $sizefl
      }
    fi  #}
    echo ""


    # try and wrap up any finished packages

    for pkgname in $pkgnames ; do  #{
      pkgRoot=./install/pkgs/$pkgname
      test -f $pkgRoot.nok -a -f $tmp/pkginfo.ld$$ ||{
        echo "Sl-12: $0 $pkgname tmp files not found"  1>&2
        continue
      }
       if [ `wc -l < $pkgRoot.nok` -gt \
           `egrep -c "^$pkgname " $tmp/pkginfo.ld$$` ]; then  #{
       # Run "exe" (POST_LOAD)
    
         phase=POST_LOAD; 	export phase
         if [ -s $pkgRoot.exe ]; then #{
           echo "Executing $pkgname control program ($phase)" \
    				>> $loadLog
    		    
           if PKGNAME=$pkgname $pkgRoot.exe < $trmdev; then  #{
              echo "$pkgname control program ($phase) successful" \
    					>> $loadLog
           else
              echo "
SL-10: Installation of $pkgname declined by control program ($phase)
Installation of $pkgname has failed"		| tee -a $loadLog	1>&2
              $BOURNE $bin_dir/delete_fls $pkgname
              if [ ! -z "$pkgflag" ]; then
                echo "Installation of $pkgname failed" >> $history
              fi
              continue
          fi  #}
        fi  #}
        sed -n '1p' $pkgRoot.nok > $pkgRoot.ok
        if [ ! -z "$pkgflag" ]; then
          echo "$pkgname installed successfully" >> $history
        fi
        products=`awk '$1 == "'$pkgname'" {print $2}' $info`
        for product in $products ; do  #{
          awk '$1 == "'$pkgname'" && $2 == "'$product'" { print $2, $3,$4  }' $info >> ${pkgRoot}.ok
        done  #}
        $Rm $pkgRoot.nok
        LoadPercent=`expr $addSize \* 100  / $totalSize`
        test $LoadPercent -eq 0 && LoadPercent=1
        echo "Installation of $pkgname complete"  | tee -a $loadLog
        echo "Total Installation $LoadPercent % done" | tee -a $loadLog
        if [ -z "$pkgflag" ]; then  #{
          $BOURNE $bin_dir/check_pdtok $info
        fi  #}
      fi  #}
    done  #}
  done #}



  #This is for making configure the default menu
  test -s $tmp/defcp && {
    cat < $tmp/defcp |
    {	
      while read pkgdesc pkgname rest;do  #{
        pkgRoot=$Proot/install/pkgs/$pkgname
        if [ "$defaultConfigOpt" -eq  0 ]; then  #{
          if [ -f $pkgRoot.att ]; then  #{
            if grep "CONFIGLEVEL=" $pkgRoot.att > /dev/null; then  #{
              if grep "CONFIGLEVEL=NONE" $pkgRoot.att > /dev/null; then #{
                defaultConfigOpt=0; echo 0 > $tmp/defconfig.opt;
              else
                defaultConfigOpt=1; echo 1 > $tmp/defconfig.opt;
             fi  #}CONFIGLEVEL=NONE
           fi  #}CONFIGLEVEL=
  		   
           if [ $defaultConfigOpt -eq 0 ]; then  #{
             if grep "USER_CONFIG=1" $pkgRoot.att > /dev/null; then  #{
               defaultConfigOpt=1; echo 1 > $tmp/defconfig.opt;
             else
               defaultConfigOpt=0; echo 0 > $tmp/defconfig.opt;
             fi  #}
           fi  #}
         fi  #}pkgRoot.att condition
       fi   #}defaultConfigOpt condition
     done  #}
    }
  }
  rm -f $tmp/defcp

  test -z "$skipTape" && $close_tape <$trmdev
} || exit $?

grep "SKIPTAPE" $loadLog | awk '{ print $2 }' | sort -u > /tmp/skiptape$$
test -s /tmp/skiptape$$ && {
  echo "
During this installation you skipped the following media(s):"
  /bin/cat /tmp/skiptape$$
}

$jsr EchoN "${NL}Checking the installed products...${NL}"

if [ -z "$pkgflag" ]; then #{
  if [ -s $selprodfile ]; then #{
    while read pdtdesc pkgname pdtname pdtsize platform FMrelease ; do  #{
      echo "$pkgname $pdtname $platform $FMrelease"
    done < $selprodfile  > $tmpfl
    if [ -s $tmpfl ]; then
      $jsr EchoN "${NL}Updating status of installed products...${NL}"
      $BOURNE $bin_dir/check_pdtok $tmpfl
    fi #}
    $Rm $selprodfile $tmpfl
  fi #}
fi #}
  

$jsr Intr_Clean
  


msg="
The products you selected have now been loaded. Place your CD-ROMs
(or tapes) containing the Cadence products in a secure, yet accessible
location.
 
Continue the installation by configuring the products you just loaded.

Always configure licensing before configuring libraries.

From the main menu, select Configure Installed Products if it is
selectable.

For more information, see the Cadence Installation Guide.

Check the ~install/tmp/install.history file for the list of 
products affected by this install.
"


if $useGUI; then
   $BOURNE $bin_dir/msgDialog.sh "$msg"
else
   echo "$msg"
fi
test -s $sizefl && $Rm $sizefl
$Rm $tmp/pkginfo.ld$$ /tmp/skiptape$$ $tmp/selprodfile 
date >> $loadLog
exit 0
