#!/bin/sh
# 
# copy-or-stash.sh - copy a file to a dir or stash-dir
################################################################
# Copyright (C) 2001, 2002 Tom Lord
# 
# See the file "COPYING" for further information about
# the copyright and warranty status of this work.
# 

set -e 

################################################################
# special options
# 
# Some options are special:
# 
#	--version | -V
#	--help | -h
# 
if test $# -ne 0 ; then

  for opt in "$@" ; do
    case $opt in

      --version|-V) exec larch --version
                    ;;


      --help|-h)
		printf "*copy a file to a dir or stash-dir\\n"
		printf "usage: copy-or-stash [options] file dir stash-dir\\n"
		printf "\\n"
		printf " -V --version                  print version info\\n"
		printf " -h --help                     display help\\n"
		printf "\\n"
		printf " -e --errname errname          specify a name for error messages\\n"
		printf "\\n"
		printf "FILE should be a relative path name and may be a file or directory.\\n"
		printf "\\n"
		printf "If \'dirname FILE\` exists in DIR, copy FILE there.  If FILE is a\\n"
		printf "directory, \`mkdir FILE\` there.\\n"
		printf "\\n"
		printf "Otherwise, \`mkdir -p\' in the STASH-DIR, and copy or mkdir FILE\\n"
		printf "there.\\n"
		printf "\\n"
		exit 0
      		;;

      *)
		;;
    esac
  done
fi

################################################################
# Ordinary Options
# 
# 

errname=copy-or-stash

while test $# -ne 0 ; do

  case "$1" in 

    -e|--errname)	shift
			if test $# -eq 0 ; then
			  printf "copy-or-stash: -e (--errname) requires an argument\\n" 1>&2
			  printf "\\n" 1>&2
			  printf "Try --help\\n" 1>&2
			  exit 1
			fi
			errname="$1"
			shift
			;;
			
    -*)			printf "copy-or-stash: unrecognized option (%s)\\n" "$1" 1>&2
			printf "\\n" 1>&2
			printf "Try --help\\n" 1>&2
			exit 1
			;;

    *)			break
    			;;
  esac

done



################################################################
# Ordinary Arguments
# 

if test $# -ne 3 ; then
  printf "usage: copy-or-stash [options] file dir stash-dir\\n" 1>&2
  printf "\\n" 1>&2
  printf "Try --help\\n" 1>&2
  exit 1
fi

file="$1"
shift

dir="$1"
shift

stash_dir="$1"
shift

################################################################
# Sanity Check and Process Defaults
# 

here="`pwd`"

cd "$dir"
dir="`pwd`"
cd "$here"

cd "$stash_dir"
stash_dir="`pwd`"
cd "$here"

dirpath="`dirname \"$file\"`"

if test -e "$dir/$dirpath" ; then
  destdir="$dir/$dirpath"
else
  destdir="$stash_dir/$dirpath"
  mkdir -p "$destdir"
fi

dest_file="$destdir/`basename \"$file\"`"

if test -e "$dest_file"  ; then
  printf "%s: file already exists\\n" 1>&2
  printf "  file: %s\\n" "$dest_file" 1>&2
  printf "\\n" 1>&2
  exit 1
fi

################################################################
# Do It
# 

cd "$here"

if test -d "$file" ; then
  mkdir "$dest_file"
else
  cp "$file" "$dest_file"
fi

