#! /bin/sh

# This script is designed to manage the CD-ROM drive on a server, for
# clients who are doing remote installs from the CD.  It handles most
# of the messy problems of determining whether a CD is installed, that
# it is mounted at the expected place (and handling the case where it
# was already mounted somewhere else), and of keeping the CD from being
# ejected when it is in use.
# It also handles the case where multiple CD drives exist.
# It requires that mediad be installed and usable, and gives up if
# it can't start mediad for the drive with the necessary mount point.

# There are two main modes of operation.  The most common allows use
# by non-super users, and simply mounts, busies, and ejects the media
# when appropriate, and indicates why it can't be ejected in case it
# is busy (whether it is still in use by another workstation, for example).


# the intent is that one copy be run on the server for each workstation that
# is being installed from a CD-ROM on the server.  The prompts that
# are likely to be present for some time have the program name, and
# the name of the host that the script is an agent for, and require
# a specific input, not just a RETURN.  Where "CD-ROM" is used, the
# drive or something pertaining to the drive is being discussed; where
# "CD" is used, it is the actual media.

# The other major mode requires superuser privileges, and is needed when
# either the mediad program isn't running, or is in use by one of the
# cdplayer programs, etc.  It does this by using su root -c 'cmd'
# It terminates (after asking) any other programs that might have the CD open
# (cdplayer, etc), and then starts mediad with the a prompted for
# mount point

# This script has some rather intimate knowledge of the messages output
# from mediad and eject.  This script has been modified to use mediad.
# I've changed all the calls and comments, but the variable and function
# names are still cdromd oriented.  Mediad is mostly the same as cdromd,
# except that it monitors all the removable media devices in a single
# deamon.  The -q, -m, and -k options used in this script have slightly
# different meanings for mediad, but the effect is about the same.

# NOTE: all of the # { and # } comments are intended to make it 
# easier to find loops with the % command in vi
# shell functions all come first, search for 'Main line code' to
# find mainline stuff


# do our initialization
init()
{
   # be paranoid on startup
   IFS='    
   '
   oIFS="$IFS"  # save for restores at various points
   oPATH=$PATH # for possible exec of ourselves
   PATH=/usr/sbin:/usr/bsd:/bin:/usr/bin:/usr/etc:/etc
   export PATH IFS

   # check for this early
   if which -f mediad > /dev/null 2>&1
   then :
   elif issuperuser || [ ! -r /usr/etc/mediad ]
   then
      echo '\007You do not seem to have the eoe2.sw.rm_media subsystem'
      echo installed on the server.  You must have it to be able
      echo to do remote installs from CD-ROM.
      echo Please install this subsystem on the server, then try again.
      exit 1
   else
      echo '\007You must be root to use cdinstmgr'
      exit 1
   fi
      
   startedcdromd=0
   myname=`basename $0` # name to look for to check for CD busy by installs
   myhost=`hostname`
   if [ -x /usr/bin/domainname ]
   then
    myfqdn=$myhost.`domainname`
   else
    myfqdn=$myhost
   fi

   chkargs $@
}


# make sure hostname given isn't the server name
# only half hearted, and not critical, but should
# catch most errors in understanding
chkhostname()
{
   if [ "$hostname" = "$myhost" -o "$hostname" = "$myfqdn" ]
   then
      echo I need the name of the machine you will be installing on
      echo NOT the name of this machine.  If you are doing a local install
      echo from CD-ROM on this machine, you do not need this program.
      return 1
   else
      return 0
   fi
}


chkargs()
{
   # Need hostname in arg list to show in listcdusers
   if [ $# -ne 1 ]
   then
      while :
      do
         echo Hostname of client that is installing from CD on $myhost? \\c
         read hostname
         if [ -n "$hostname" ]
         then
            if chkhostname
         then
               PATH=$oPATH exec $0 $hostname
            fi
         fi
      done
   else
      hostname=$1
     if chkhostname
     then :
     else # re-exec with no arg so they are prompted
       PATH=$oPATH exec $0
     fi
   fi
   Ptmp=/tmp/.CD$hostname.$$
}


# finish up and exit
cleanup()
{
   rm -f $Ptmp ${Ptmp}*
   cd / # in case here on signal
      if [ $startedcdromd -eq 1 ]
      then
         if answeryes "$prompt the CD-ROM daemon was started by you,\n\tleave it running?"
         then
            exit 0
         else
            if issuperuser
            then
               mediad -ir $cdromdev
            else
               echo You will need to be superuser to clean up
            # echo in su cmd, in case no root password
               su root -c "echo Stopping mediad daemon monitoring of $cdromdev; mediad -ir $cdromdev"
            fi
         fi
      fi
      exit 0
}


# are we root?
issuperuser()
{
   case "`id`" {
   uid=0\(* | euid=0\(*) return 0;;
   *) return 1;;
   }
}


# given a scsi adapter and id, check to see if that device
# is mounted, either directly, or via mediad; won't work
# if they have made their own device like /dev/cdrom
chkmount()
{
   mount="`mediad -m /dev/scsi/sc$1d$2l0 2>/dev/null`"
   if [ $? -eq 0 -a -n "$mount" ]
   then
         cdromdison=1
      return 0;
   fi
      cdromdison=0
   if mount="`mount 2>/dev/null | grep /dev/dsk/dks$1d$2s7`"
   then
      set $mount
      shift 2
      mount=$1
      return 0
   fi
   mount= # paranoia
   return 1
}

# show the products on the mounted CD
showproducts()
{
 nomedia=0 isinstcd=0
 echo The CD-ROM at controller $1, ID $2 is mounted at $mount
 idbs="`2>/dev/null cd $mount/dist; echo *.idb | grep -v '*.idb'`"
 if [ -n "$idbs" ]
 then
    isinstcd=1
    echo "It appears to be an installable CD with the following products:"
    (cd $mount/dist; ls -C `echo "$idbs" | sed 's/\.idb//g'`)
   echo ''
   else
      if mount | grep $mount > /dev/null 2>&1
      then
         echo It does not seem to be an installable CD
      else
         echo But no CD appears to be in the drive, or it is in use
      echo by some program that keeps it from being mounted.
         nomedia=1
      fi
 fi
}

# find a CD player to use; if more than one, have user select one
findcd()
{
   ncd=0 IFS="$IFS:" 
   hinv | (   while read cd unit id on scsi ctlr adap rest # {
      do if [ "$cd" = CDROM ] # {
         then ncd=`expr $ncd + 1`
            cdids="$cdids $adap,$id"
         fi
      done # }
      IFS="$oIFS"
      if [ $ncd -eq 0 ] # {
      then echo '\007No CD-ROM drive found.  It must be both attached to'
         echo the system, and powered on when the system is booted.
         exit 1
      elif [ $ncd -eq 1 ] # good, just one
         then echo $cdids > /tmp/.CD$$
         exit 0
      else #  } { # oh well, we have to find the right one
         for i in $cdids
         do # {
             IFS="$IFS,"
             set `echo $i`; IFS="$oIFS"
             if chkmount $1 $2
             then
                  showproducts $1 $2
             fi
         done # }
         while :
         do # {
            echo '\nPlease choose one of the CDROM drives by number in ():'
            which=1
            for i in $cdids
            do # {
               IFS="$IFS,"
            set `echo $i`;IFS="$oIFS"
               echo "($which)  CD-ROM at controller $1, ID $2"
               which=`expr $which + 1`
            done # }
            read number < /dev/tty
            if [ -n "$number" -a "$number" -gt 0 -a "$number" -lt $which ]
            then # {
               set $cdids
               number=`expr $number - 1`
               shift $number
               echo $1 > /tmp/.CD$$
               exit 0
            fi # }
         done # }
      fi # }
   ) # }
   if [ $? -ne 0 ]
   then exit $?
   fi

   set `sed 's/,/ /' /tmp/.CD$$`
   ADAP=$1 CD=$2
   rm -f /tmp/.CD$$
   IFS="$IFS,"
   chkmount $ADAP $CD
  cdromdev=/dev/scsi/sc${ADAP}d${CD}l0
  if [ -n "$mount" ]
  then # show what is there (if mounted); set state
   showproducts $ADAP $CD
   fi

   IFS="$oIFS"
}

# list all of the programs using the cd
# not a perfect way to get commands and options, but few commands will
# have this particular pattern in their args.
listcdusers()
{
  busy=1
  list="`/etc/fuser -q /dev/*dsk/dks${ADAP}d${CD}s7 $cdromdev`"
  if [ -n "$list" ]
  then
    ps -f -p $list | sed -e 1d -e /defunct/d -e 's/.*[0-9]:[0-9][0-9] //' > $Ptmp
    if grep $myname $Ptmp > $Ptmp.1
    then
      if [ -s $Ptmp.1 ]
      then
         echo The CD-ROM drive is in use by installs from the following host'(s)':
         sed "s/.*$myname //" $Ptmp.1 | fmt
            busy=0
       fi
    fi
    if grep -v $myname $Ptmp > $Ptmp.2
    then
      sed /grep?-v?$myname/d $Ptmp.2 > $Ptmp.3
      if [ -s $Ptmp.3 ]
      then
         echo The CD-ROM drive is in use by these programs '(other than installs)':
         cat $Ptmp.3
            busy=0
       fi
    fi
  fi
  return $busy
}


# check for programs other than mediad on the devscsi device
chkotherprogs()
{
  list="`/etc/fuser -q $cdromdev`"
  if [ -n "$list" ]
  then # { check to see if progs other than mediad are using it,
   # such as the cdplayer program
    ps -f -p $list | sed -e 1d -e /mediad/d -e /defunct/d -e 's/.*[0-9]:[0-9][0-9] //' > $Ptmp
   if [ -s $Ptmp ]
   then
      echo 'The CD-ROM is in use by the following program(s), which'
      echo may interfere with the installation.
      cat $Ptmp
      if answeryes 'Do you want to have this program terminate them?'
      then
         if issuperuser
         then
           fuser -kq $cdromdev
         else
            echo You need to be superuser to do so
            su root -c "echo Terminating them as superuser;fuser -kq $cdromdev > /dev/null"
         fi
      fi
   fi #
  fi # }
}


# start the mediad daemon for this device, so non-supers can do ejects, etc.
startcdromd()
{
   if [ ! -d $mount ]
   then
      if mkdir -p $mount
      then :
	  else
         echo  Mount point $mount exists, but is not a directory, bye
         exit 1
      fi
   fi

   su root -c "echo Checking mediad for $cdromdev; mediad -q $cdromdev"
   case $? {
   2|6|10) # already running; logic guarantees the mount pt agrees
      return ;;
   }

   if issuperuser
   then
      if mediad -ip $cdromdev $mount
      then
         startedcdromd=1
      else
         # we are already superuser, so don't keep trying
         echo Failed to start mediad, giving up
         exit 1
      fi
   else
      echo CD-ROM daemon needs to be started, and you need
      echo to be superuser to start it.  Starting su command
      startcdromasroot
      startedcdromd=1
   fi
   sleep 15 # give it time to mount if media present
}

# same as startcdromd, but become root first, check differently
# for success; fortunately, even when mediad is started after
# a manual mount, eject and re-mount work even for non-superuser
# as long as the mountpoints are the same.
# For the asroot case, we really need for it to start, which is
# why we keep trying.
# If the start fails, it is safe to try and restart, even if
# the previous one is still busy, since a second one will quietly exit
startcdromasroot()
{
   
   while :
   do 
      # echo inside su, in case there is no root password, since
      # we just told them they had to be superuser
	  # sleep is to give mediad a chance to start
	  # -q requires that you be root also, so do all at once...
      su root -c "echo Starting CD-ROM daemon;mediad -ip $cdromdev $mount;
		  sleep 10; mediad -q $cdromdev"
      case $? {
      2|6|10) startedcdromd=1
         return ;;
      *) echo Failed to start CD-ROM daemon, retrying ;;
      }
   done
}


# get a yes or no answer, return 0 if yes, 1 otherwise
answeryes()
{
   while :
   do
      echo "$1 (y/n) \c"
      read answer
      case "$answer" {
         n*|N*) return 1;;
         y*|Y*) return 0;;
      }
   done
}

getmountpt()
{
   if [ -n "$mount" ]
   then # { chose a CD that has a mount point, not necessarily mounted
      if [ $nomedia -ne 1 ]
      then # { check to see if it should be unmounted first
      while :
      do # {
         if answeryes 'CD is mounted, should I unmount and eject it?'
         then # {
            if [ $cdromdison -eq 1 ]
            then
               if [ $? -eq 0 -o $? -eq 4 ]
               then return
               fi
            else # { try umount
               if msg="`umount $mount 2>&1`"
               then # must be root; startup mediad for other users and loop
                  eject $mount
                  return
               else
                  case "$msg" {
                  "* busy") ;; # fall through
                  *) echo $msg # umount error message
                     exit 1 ;;
                  }
               fi
            fi # }

            echo \\007Failed to unmount $mount, it is in use
            listcdusers
            echo ''
            if answeryes '\nTry again?'
               then :
               else exit 1
            fi
         else
			echo You will need to umount and/or eject it yourself then.
            break
         fi # }
      done # }
      fi # }
   else # } {
      echo CD is not mounted, and CD-ROM daemon is not running.
      echo 'What directory do you want to use\n\t(/CDROM is normally used)? \c'
      while :
      do
         read mount
         case "$mount" {
         /*) break;;
         "") ;;
         *)  echo The mount point needs to be a full pathname ;;
         }
         echo 'What directory do you want to use? \c'
      done
   fi # }
}


# loop prompting, cd'ing on mount, wait for user to finish
# with CD, try and loop trying to eject it.  Once ejected
# return to main loop waiting for new media to be inserted
looptilldone()
{
   while :
   do # {
      while :
      do # {
         # unfortunately, once mounted, mediad always returns the
         # mount point; so we have to actually check on the fact
         # that all of the SGI installable CDs have a /dist.
         # since that dir might exist at the mount pt if unmounted
         # look for .idb files instead.
            idbs="`cd $mount/dist 2>/dev/null; echo *.idb`"
         case "$idbs" {
         '*.idb'|'')
            echo $prompt press RETURN when CD is in drive and ready \\c
            read ready
         sleep 10 # they will hit RETURN right after inserting, this
            # gives enough time that mediad will likely have mounted it
         ;;
         *) break ;; # some idb files exist
         }
      done # }

      cd $mount # keep it busy so others can't unmount
      showproducts $ADAP $CD
      echo '\nIf this is the wrong CD, type "done" immediately to use a different one'

      msg='type the word "done" when you are finished
\twith this CD, "quit" if you are completely done'
      while echo $prompt "$msg: \c"
      do # {
         read finished
         case "$finished" {
         "done") cd / # we don't want to keep it busy
            if eject $mount >/dev/null 2>&1
            then
               break
            else
               case $? {
               4) echo Someone else ejected the CD! ;;
               2) echo Unable to eject CD, it is in use:
                  if listcdusers
                  then 
                     echo ''
                     msg='type the word "done" when you think other
\tusers have finished, "quit" if you are completely done'
                  fi
                  ;;
               5) echo In use by program that does not support eject ;;
               1|3) echo Eject failed ;;
               }
            fi
            ;;
         quit) cd / # we don't want to keep it busy
            return ;;
         }
      done # }
   done # }
}


# Main line code starts here

init $@

findcd

getmountpt

prompt="CD on $mount for host $hostname:"

chkotherprogs

startcdromd

trap 'cleanup' 2 

looptilldone

cleanup
