#!/bin/csh -f

# Usage: cpln [-iR] source [target]

# Copy a source file that may be a symbolic link to target.  When the
# source is a symbolic link, a symbolic link is created to whatever
# source is linked to.  If the target is omitted, it is assumed to be
# the current directory.  Then, if the target is a directory, it is
# changed to $target/$source:t.  If this is again a directory, we exit
# with an error for trying to overwrite a directory with a link or
# file.

# -i: Interactive.  cpln will prompt for confirmation when- ever the
#     copy would overwrite an existing target.  An answer starting
#     with "y" means that the copy should proceed.  Any other answer #
#     prevents cp from overwriting target.

# -R: Recursive.  cpln will copy the directory and all its files,
#     including any subdirectories and their files to target.

# -r: Same as -R.

# Options also get passed through to cp when copying a non-link that
# is a non-directory or is not to be copied recursively.

set debug = 0

set noglob

set opts = ""
while ("$1" =~ -*)
  if ("$1" == "-" || "$1" == "--") then
    shift
    break
  endif
  set opts = ($opts $1)
  shift
end

if ($debug) echo "cpln: opts|$opts|."

echo $opts | egrep -v 'R|r' > /dev/null
if ($status) set recursive
echo $opts | egrep -v 'i' > /dev/null
if ($status) set interactive

if ($#argv < 1 || $#argv > 2) then
  echo "Usage: cpln [-iR] source-file [target]"
  exit (1)
endif

set source = "$1"
set target = "$2"
if ("$target" == "") set target = "."
if (-d "$target") set target = "$target/$source:t"

if ($debug) echo "cpln: source|$source|; target|$target|"

if (-d "$target") then
  echo "cpln: ${target}: cannot overwrite directory with link or file"
  exit (1)
endif

set link = "`ls -ld $source | sed -n 's+.* -> ++p'`"

if ($debug) echo "cpln: link|$link|"

if ("$link" == "") then # source is not a symbolic link: do regular cp or recur
  if ($?recursive && -d $source) then
    mkdir $target
    unset noglob
    if ($status) exit ($status)
    foreach file (${source}/*)
      cpln $opts "$file" "$target"
    end
    set noglob
    exit ($status)
  endif
  cp $opts $source $target
  exit ($status)
endif

if (-e $target) then
  set overwrite = y
  if ($?interactive) then
    echo 'cpln: overwrite `'"$target'? "
    set overwrite = $<
  endif
  if ("$overwrite" !~ y*) exit (1)
  rm $target
endif

ln -s $link $target
