#! /bin/csh -f

# shell script for installing files	[ mbp 5/13/90 ]

# usage: instl [ -cp copy ] [ -mkdir ] destdir files

# This script installs files in destdir.  If the -cp option is
# present, copy is used to do the installation; copy defaults to 'cp'.
# If the -mkdir option is present and destdir does not exist, we
# attempt to create it before installing.  If a one of the files
# already exists in the destination directory it is removed before the
# copy command is performed, unless it is identical to the file to be
# installed, in which case a notice is printed and nothing is done
# with that file.  Error messages indicating what the problem is are
# printed on stdout if the installation cannot be completed.
#
# If destdir is the empty string, the script returns immediately without
# doing anything or generating an error.

#
# parse arguments
#

if ( $#argv < 2 ) goto usage
if ( "$1" == "-cp" ) then
  set copy = "$2"
  shift ; shift
else
  set copy = "cp"
endif
if ( "$1" == "-mkdir" ) then
  set mkdir
  shift
endif
if ( $#argv < 2 ) goto usage
set destdir = $1
shift
set files = "$*"
set remainingfiles = ( $files )

#
# Check validity of destdir, creating it if necessary when -mkdir is present
#
if ( "$destdir" == "" ) exit 0
if -e $destdir then
  if ! -d $destdir then
    set reason = "destination directory '$destdir' is not a directory"
    goto badinstall
  endif
  if ( (! -w $destdir) || (! -x $destdir) ) then
    set reason = "you can't write in destination directory '$destdir'"
    goto badinstall
  endif
else
  if $?mkdir then
    echo mkdir $destdir
    if ! { mkdir $destdir } then
      set reason = "destination directory '$destdir' cannot be created"
      goto badinstall
    endif
  else
    set reason = "destination directory '$destdir' does not exist"
    goto badinstall
  endif
endif

foreach file ( $files )
  if -e $destdir/$file then
    if { cmp -s $file $destdir/$file } then
      echo "'$file' and '$destdir/$file' are identical (not re-installed)"
      goto endofloop
    else
      /bin/rm -f $destdir/$file
    endif
  endif
  echo "$copy $file $destdir/$file"
  if ! { $copy $file $destdir/$file } then
    set reason = "I can't install file '$file' in directory '$destdir'"
    goto badinstall
  endif
  endofloop:
    shift remainingfiles
end

exit 0

usage:
  echo 'usage: instl [ -cp copy ] [ -mkdir ] destdir files'
  exit -1

badinstall:
  echo "Installation of"
  echo "  $remainingfiles"
  echo "cannot be completed because"
  echo "  $reason."
  echo "Try installing again after correcting this problem."
  exit -1
