#
# usage:        util.sh
#
# abstract:     This Bourne Shell script of utility functions for
#		the installer.
#
# note(s):      1. This routine must be called using a . (period)
#
# Copyright (c) 1998 by The MathWorks, Inc.
# $Revision: 1.6 $  $Date: 1998/12/22 22:48:59 $
#----------------------------------------------------------------------------
#
#=======================================================================
# Outside Global variables:
#
#   batch  - clear_screen
#   mathlib_only, cppmath_only, MATLAB - clean_alone, clean_install
#   whichi, extract_only, extract_fix_only  - finish_install
#   
# Inside Globals variables:
#
# Outside Functions:
#
# Functions:
#
#   actualpath ()
#   center_line ()
#   clean_alone ()
#   clean_install () 		<- [temp_file, temp_file2]
#   clean_temp_areas ()
#   clear_screen ()         
#   echon ()
#   finish_install ()
#   get_archlist ()		<- imbed archlist.sh
#   get_oldname ()
#   get_version ()
#   is_superuser ()
#   make_path ()		-> [msg]
#   merge_license ()
#   premature_finish ()
#   query_to_continue ()
#   search_path ()
#
# Obsolete files:
#
#   actualp.sh
#   center.sh
#   cleanup.sh
#   cont.sh
#   fin.sh
#   mklicdat.sh (part of)
#   oldname.sh
#   searchp.sh   
#   
#=======================================================================
    actualpath () { # Writes the actual file path of the argument to
		    # standard output.  Only a real existing file returns
		    # a non-null value.
		    #
		    # Always returns a 0 status.
		    #
		    # usage: actualpath file
		    #
	File=$1
	Filepath=
	lsCmd=`ls -ld $File 2>/dev/null`
        if [ "$lsCmd" ]; then
#
# Check for link portably
#
	    if [ `expr "$lsCmd" : '.*->.*'` -eq 0 ]; then
    	        if [ ! -d $File ]; then
	            Filepath=$File
                fi
            else
#
# A directory link?
#
                (cd $File) > /dev/null 2>&1
                if [ $? -eq 0 ]; then
	            :
                else
#
# Now it is either a file, link to a file, or still a bad path.
#
	            cpath=`/bin/pwd`
                    localFile=$File
#
# Follow up to 8 links before giving up. Same as BSD 4.3
#
	            n=1
    	            while [ $n -le 8 ]
    	            do
#
# Get directory correctly!
#
   	                newDir=`echo "$localFile" | awk '
#-----------------------------------------------------------------------
		{ tail = $0
                  np = index (tail, "/")
                  while ( np != 0 ) {
                      tail = substr (tail, np + 1, length (tail) - np)
                      if (tail == "" ) break
                          np = index (tail, "/")
                  }
                  head = substr ($0, 1, length ($0) - length (tail))
                  if ( tail == "." || tail == "..")
                      print $0
                  else
                      print head
                }'`
#-----------------------------------------------------------------------
	                if [ ! "$newDir" ]; then
	                    newDir="."
	                fi
	                (cd $newDir) > /dev/null 2>&1
	                if [ $? -ne 0 ]; then
		            break
	                fi
	                cd $newDir
	                newDir=`/bin/pwd`
	                newBase=`expr //$localFile : '.*/\(.*\)' \| $localFile`
                        lsCmd=`ls -l $newBase 2>/dev/null`
	                if [ ! "$lsCmd" ]; then
		            break
	                fi
#
# Check for link portably
#
	                if [ `expr "$lsCmd" : '.*->.*'` -ne 0 ]; then
	                    localFile=`echo "$lsCmd" | awk '{ print $NF }'`
	                else
#
# It's a file
#
	                    Filepath=$newDir/$newBase
	                fi
		        n=`expr $n + 1`
    	            done
    	            cd $cpath
	        fi
	    fi
        fi
	echo $Filepath
	return 0
    }
#=======================================================================
    center_line () { # Takes the input string argument and centers it
		     # in 80 characters to standard output.
		     #
		     # Always returns a zero status.
                     #
                     # usage: center_line string
                     #
	echo "$1" | awk '
#-----------------------------------------------------------------------
# blankhead is 40 characters
#
    BEGIN { blankhead = "                                        " }
	  { lend2 = 40 - (length($0) / 2 - length($0) % 2)
	    print substr(blankhead,1,lend2) $0 }'
#-----------------------------------------------------------------------
#
	return 0
    }
#=======================================================================
    clean_alone () { # Cleans out unneeded directories for standalone
                     # case. 
                     #
		     # Standalone mathlib/cppmath: (need only)
		     #
		     #    $MATLAB/extern
		     #    $MATLAB/bin
		     #    $MATLAB/etc/license.dat -> $MATLAB/license.dat
		     #    $MATLAB/install_matlab.out
		     #    $MATLAB/ftp
		     #    $MATLAB/help
		     #    $MATLAB/license.txt
		     #
		     #    if -f $MATLAB/mathlib.html then
		     #        cp $MATLAB/mathlib.html $MATLAB/helpdesk.html
		     #
		     # Call clean_install to remove:
		     #
		     #    $MATLAB/install_matlab
		     #    $MATLAB/install
                     #
                     # Always returns a 0 status.
                     #
                     # usage: check_alone
                     #
        if [ "$mathlib_only" = "1" -o "$cppmath_only" = "1" ]; then
#
# Set trap to ignore signals
#
	    trap "" 1 2 3 15
#
	    standalone=""
            if [ "$mathlib_only" = "1" ]; then
		standalone="'mathlib' "
	    fi
            if [ "$cppmath_only" = "1" ]; then
		standalone="$standalone'cppmathlib' "
	    fi
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
echo ''
echo "    Note: Cleanup for standalone $standalone..."
echo '' 
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
	    if [ -f $MATLAB/etc/license.dat ]; then
#
# Clean out SERVER, DAEMON, and any unused FEATURE/INCREMENT lines when making
# the copy
#
	        cat $MATLAB/etc/license.dat | sed \
		    -e "/0123456789ABCDEFGHIJ/d" \
		    -e "/SERVER/d" \
		    -e "/DAEMON/d" > $MATLAB/license.dat
	        chmod 644 $MATLAB/license.dat
	    fi
#
# If help/mathlib.html exists make a copy as help/helpdesk.html
#
	    if [ -f $MATLAB/help/mathlib.html ]; then
		cp $MATLAB/help/mathlib.html $MATLAB/help/helpdesk.html
	    fi
#
#///////////////////////////////////////////////////////////////////////
            xlist='. .. bin extern ftp help install install_matlab install_matlab.out license.dat license.txt'
#///////////////////////////////////////////////////////////////////////
#
	    echo $xlist > $temp_file
	    (cd $MATLAB; ls -a) >> $temp_file
#
	    cat $temp_file | awk '
#-----------------------------------------------------------------------
    NR == 1 { for (i = 1; i <= NF; i = i + 1) a[$i] = 1; next}
	    { if (a[$1] != 1) print $1 }' > $temp_file2
#-----------------------------------------------------------------------
	    (cd $MATLAB
	     while read path
             do
		 rm -rf $path
	     done) < $temp_file2
#
	    rm -f $temp_file $temp_file2
#
        fi
	return 0
    }
#=======================================================================
    clean_install () { # Cleans out the installation files.
		       #
		       # Remove:
		       #
		       #    $MATLAB/install_matlab
		       #    $MATLAB/install
		       #
                       # Always returns a 0 status.
                       #
                       # usage: clean_install
                       #
	cd $MATLAB
	if [ "$mathlib_only" = "1" -o "$cppmath_only" = "1" ]; then
	    exec /bin/rm -rf install_matlab install
        fi
	return 0
    }
#=======================================================================
    clean_temp_areas () { # Removed any temporary files and directories.
		          #
                          # Always returns a 0 status.
                          #
                          # usage: clean_temp_areas
                          #
        rm -rf $temp_file $temp_file2a $temp_file2b $temp_file2 $temp_file3 $temp_file4 $temp_file5
        rm -rf $MATLAB/update/$$a $MATLAB/update/ftp $LSCREEN
	rm -rf $temp_boot
	return 0
    }
#=======================================================================
    clear_screen () { # Clear the screen if no arg and not in batch.
                      # Always output one line in case clear doesn't
                      # work.
                      #
                      # Always returns a 0 status.
                      #
                      # usage: clear_screen arg
                      #
#-----------------------------------------------------------------------
        echo ''
#-----------------------------------------------------------------------
        if [ $# -eq 0 ]; then
            if [ "$batch" != "1" ]; then
                clear
            fi
        fi
        return 0
    }
#=======================================================================
    echon () { # Echo's out a message without the newline so that the
               # user can be prompted.
               # 
               # Always returns a 0 status.
               # 
               # usage: echon mesg
               # 
        if [ "`echo -n`" != "" ]; then
            echo "$1\c"
        else
            echo -n "$1"
        fi
        return 0
    }
#=======================================================================
    finish_install () { # Finishes the install.
		        #
		        # Always returns a 0 status
		        #
			# usage: finish_install
		        #
#
#			Finished install [2]
#			----------------
#
	clean_temp_areas
#
	clean_alone
#
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
echo ''
echo '    ---------------------------------------------------------------------'
echo '    | Finished! This completes the:                                     |'
echo '    |                                                                   |'
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        case "$whichi" in
	    1)
	       if [ "$extract_only" = "1" ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
echo '    |                  NORMAL install (extract files only)              |'
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	       elif [ "$extract_fix_only" = "1" ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
echo '    |                  NORMAL install (extract files with update)       |'
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	       else
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
echo '    |                  NORMAL install                                   |'
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	       fi
	       ;;
	    2)
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
echo '    |                  CLIENT install                                   |'
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	       ;;
	    3)
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
echo '    |                  CLIENT WITH LICENSE MANAGER install              |'
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	       ;;
	    4)
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
echo '    |                  LICENSE MANAGER ONLY install                     |'
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	       ;;
        esac
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
echo '    |                                                                   |'
echo '    |           for this host.                                          |'
echo '    ---------------------------------------------------------------------'
echo ''
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#
        clean_install
#
        exit 0
    }
#=======================================================================
    get_archlist () { # Outputs the value of the archlist variable,
		      # ARCH_LIST.
                      #
                      # Always returns a 0 status.
                      #
                      # usage: get_archlist
                      #
#========================= archlist.sh (start) ============================
#
# usage:        archlist.sh
#
# abstract:     This Bourne Shell script creates the variable ARCH_LIST.
#
# note(s):      1. This file is always imbedded in another script
#
# Copyright (c) 1997-1998 by The MathWorks, Inc.
# $Revision: 1.3 $  $Date: 1998/11/03 22:06:40 $
#----------------------------------------------------------------------------
#
    ARCH_LIST='sol2 hp700 alpha ibm_rs sgi sgi64 lnx86'
#========================= archlist.sh (end) ==============================
	echo $ARCH_LIST
        return 0
    }
#=======================================================================
    get_oldname () { # This Bourne Shell script given oldname returns the
                     # unique name in old/ so that oldname can be placed
		     # there without overwriting any other file. The
		     # original oldname and old/ are in the directory
		     # specified by dir_oldname.  The format of a file
                     # in old/ is:
		     #         oldname.date.#
                     # date is taken from the file. If old/ does not
		     # exist it is created. We assume the file exists.
                     #
                     # note(s): 1. The variable 'oldname' holds the
		     #             filename.
                     #		3. The variable 'dir_oldname' holds the
		     #             directory where oldname and old/
		     #             exist.
                     #		4. date = ddmmmyy (mmm in lowercase)
		     #
                     # Always returns a 0 status.
                     # 
                     # usage: get_oldname dir_oldname file_oldname
                     # 
	dir_oldname=$1
	file_oldname=$2
#
        if [ ! -d $dir_oldname/old ]; then
	    mkdir $dir_oldname/old
	    chmod 755 $dir_oldname/old
        fi
#
        daymonth=`(cd $dir_oldname; ls -l $file_oldname | awk '{ print $(NF-2) $(NF-3) }' | tr '[A-Z]' '[a-z]')`
	year=`date | awk '{ print $NF }'`
	date=$daymonth$year
#
	nfiles=`(cd $dir_oldname/old; ls $file_oldname.$date.* 2>/dev/null) | awk '
#----------------------------------------------------------------------------
    BEGIN { maxn = 0; digits = "0123456789" }
          { n = split($0,a,".")
	    if (n >= 3) {
	        m = a[n]
		for (i = 1; i <= length(m); i = i + 1)
		    if (index(digits,substr(m,i,1)) == 0) 
			break
	        if (i == length(m) + 1) 
		    if (m > maxn)
			 maxn = m 
	    }
	  }
    END { print maxn }'`
#----------------------------------------------------------------------------
        nfiles=`expr $nfiles + 1`
	echo $file_oldname.$date.$nfiles
#
	return 0
    }
#=======================================================================
    get_version () { # Outputs the value of the version variable,
                     # version.
                     #
                     # Always returns a 0 status.
                     #
                     # usage: get_version
                     #
        echo $version
        return 0
    }
#=======================================================================
    is_superuser () { # Determines whether the current user is superuser
		      # or not. We assume uid=0 is always superuser.
		      # If id does not exist we try to create a file
		      # called $$check in / and delete it.
		      # 
                      # Returns a 0 status if superuser else 1.
                      #
                      # usage: is_superuser
                      #
        pathlist=`search_path id`
        if [ "$pathlist" != "" ]; then
            user=`id`
            if [  `expr "$user" : 'uid=0('` -ne 6 ]; then
		return 1
	    else
		return 0
	    fi
	else
#
# Command 'id' is not on the path. Try the file check method.
#
	    (cat /dev/null > /$$check) > /dev/null 2>&1
	    if [ $? -eq 0 ]; then
		rm -f /$$check
		return 0
	    else
		return 1
	    fi
	fi
    }
#=======================================================================
    make_path () { # Create all directories in the path. The
		   # permissions will be set to 755. Write any
		   # error message to the msg variable.
		   #
                   # Always returns a 0 status unless the directory
		   # could not be created.
                   #
                   # usage: make_path path
                   #
#	
# Absolute [/] or relative [.]
#
        startdir=`expr "//$1" : '//[ 	]*\(/\).*' \| '.'`
#
# Always add a /. to force mpath to always have something
#
	mpath=`echo $1/. | tr "/" " "`
	(cd $startdir;
	 for dir in $mpath
	 do
	     if [ `expr "//$startdir" : '//.*/[ 	]*$'` -ne 0 ]; then
		 dirpath=$startdir$dir
	     else
		 dirpath=$startdir/$dir
	     fi
	     if [ -d $dirpath ]; then
		startdir=$dirpath
		continue
	     fi
	     mkdir $dirpath
	     if [ $? -ne 0 ]; then
		break
	     fi
	     chmod 755 $dirpath
	     startdir=$dirpath
	done) 2>$temp_file
        msg="`cat $temp_file`"
	rm -f $temp_file
	if [ "$msg" != "" ]; then
	    return 1
	fi
	return 0
    }
#=======================================================================
    merge_license () { # Merge license file into template file and
		       # write result to standard output. There is
		       # 'EOF' that separates the two files.
		       #
		       # Always returns a 0 status.
		       #
		       # usage: merge_license template_file license_file
		       #
#
# If license file already has SERVER lines, then assume that they are
# correct and use those. Always use the DAEMON line from the template
# file. The two exceptions that must be changed
#
#	server port number comes from the template file
#	daemon options file comes from the license file
#
# They should merge these into the template file.
#
	cat $1 $2 | awk '
#----------------------------------------------------------------------------
    BEGIN { state = 0; nc = 0; nf = 0; server_found = 0; nserver = 0 }
    $1 == "EOF" { state = 1; next }
	{ if (state == 0 ) { 
	      if ($1 == "SERVER") {
		  server = $0
		  if (NF == 4)
		      port = $4
		  else
		      port = ""
	      }
	      if ($1 == "DAEMON")
		  daemon = $0
	  }
	  else if ($1 == "SERVER") {
	      server_found = 1	
	      nserver = nserver + 1
# fix the port in each server line
	      if ( port != "") {
	          serverv[nserver] = $1 " " $2 " " $3 " " port
	      }
	      else
	          serverv[nserver] = $0
	  }
	  else if ($1 == "DAEMON") {
# add the options file to the the daemon line if it exists
	      if (NF == 4)
		  daemon = daemon " " $4
	  }
	  else if (substr($1,1,1) == "#" && (index($2,"BEGIN") != 1 && index($2,"END") != 1)) {
	      nc = nc + 1
	      comment[nc] = $0
	  }
	  else if (($1 == "FEATURE") || ($1 == "INCREMENT")) {
	      nf = nf + 1
	      feature[nf] = $0
	  }
	  next
	}
    END { if (nc > 0) for (i = 1; i <= nc; i = i + 1) print comment[i]
	  if (server_found != 0)
              for (i = 1; i <= nserver; i = i + 1)
		  print serverv[i]
          else 
	      print server
	  print daemon
          if (nf > 0) for (i = 1; i <= nf; i = i + 1) print feature[i]
	}'
#----------------------------------------------------------------------------
	return 0
    }
#=======================================================================
    premature_finish () { # Premature finish
		          #
		          # Always returns a 0 status
		          #
			  # usage: premature_finish
		          #
#
	clean_temp_areas
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    echo ''
    echo "    $CMDNAME stopped prematurely . . ."
    echo ''
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        exit 1
    }
#=======================================================================
    query_to_continue () { # Query the user to continue if not in batch
			   # mode and no arguments.
			   #
		           # Always returns a 0 status.
		           #
			   # usage: query_to_continue arg
		           #
        if [ "$batch" = "0" -a $# -eq 0 ]; then
	    echon 'Continue? ([y]/n) '
            read ans
            if [ `expr "//$ans" : '//[Nn].*'` -gt 0 ]; then
		premature_finish
            fi
        fi
	return 0
    }
#=======================================================================
    search_path () { # Searches all the directories in your PATH for
		     # the command argument and outputs those to
		     # standard out as a list each separated by a blank.
		     #
		     # Always returns a 0 status.
		     #
		     # usage: search_path command
		     #
	cmd=$1
	vpath=`echo $PATH | tr ":" " "`
#
	pathlist=""
	for dirname in $vpath
	do
	   if [ -d $dirname/$cmd ]; then
	      pathlist="$pathlist $dirname/$cmd"
	   else
	      lscmd=`ls -l $dirname/$cmd 2>/dev/null`
	      if [ "$lscmd" ]; then
	         pathlist="$pathlist $dirname/$cmd"
	      fi
	    fi
	done
	echo $pathlist
#
	return 0
    }
#=======================================================================
