# Installs files into the given directory; has same command-line semantics
# as cp -r, except:
# 1) if the target directory doesn't exist, it creates it
# 2) it tracks all of the files installed in the file .$(TARGET_DIR) for
#    later uninstall
# 3) CVS directories are ignored
#
# usage: cyc_install file1 file2 ... target_dir
#

if [ $# -lt 2 ]; then
  echo usage: $0 -u target_dir			Install mode
  echo        $0 file1 file2 ... target_dir	Uninstall mode
  exit 1
fi

# set -x

# inst_record_name target_dir
#   calculates the install record's name based on some criteria
#   (assumes the directory is an absolute path)
inst_record_name () {
  mark=`echo $1 | sed -e 's/\//-/g'`
  echo ".inst_${mark}"
}

# get_files filelist targetdir
#   prints all of the files in the given list.  If a given file is
#   a directory, it recurses and prints the files in the directory as well.
#   Skips files with CVS in their path.  If the file does not exist,
#   it is ignored (not printed)
get_files () {
  for file in $1; do
    # regular file
    if [ -f "$file" ]; then
      echo $file $2
    # directory; recurse
    elif [ -d "$file" ]; then
      files=`find $file/* -print -prune | grep -v CVS`
      get_files "$files" "$2/`basename $file`"
    fi
  done
}

# check for mode
if [ "$1" = "-u" ]; then
  target_dir=$2
  inst_file=`inst_record_name $target_dir`

  # remove each of the files
  #
  { while true; do
      read src_file dest_file
      if [ $? != 0 ]; then break; fi
      if [ "$src_file" = "XXX" -a "$dest_file" = "XXX" ]; then
        while true; do
	  read dir
          if [ $? != 0 ]; then break; fi
          rmdir $dir
        done
        break
      else
        rm -f $dest_file/`basename $src_file`
      fi
    done
  } < $inst_file
  rm -f $inst_file

else
  # gather input files
  #
  files=
  while [ $# != 1 ]; do
    files="$files $1"
    shift
  done

  # get target directory
  #
  target_dir=$1

  # create uninstall file
  # 
  inst_file=`inst_record_name $target_dir`
  get_files "$files" $target_dir > $inst_file

  # do the install.  keep track of directories created
  #
  dirs=
  { while true; do
      read src_file dest_file
      if [ $? != 0 ]; then break; fi
      if [ ! -d "$dest_file" ]; then
        mkdir -p $dest_file
        dirs="$dest_file $dirs"
      fi
      # cp -p preserves mod times.  This is needed because OS X requires
      # .a files to have a modtime = last time ranlib was run on the file.
      cp -p $src_file $dest_file
    done
  } < $inst_file

  # output end marker and created directories
  echo "XXX XXX" >> $inst_file
  for dir in $dirs; do
    echo $dir
  done | sort -r >> $inst_file
fi
