#!/bin/zsh

pathOfDirPartOfExecPath() {
  if [[ -h "$1" ]] ; then
    local lsout="$(ls -l "$1")"
    local referent="${lsout#* -> }"
    pathOfDirPartOfExecPath "$referent"
  elif [[ -d "${1%/*}" ]] ; then
    echo "${1%/*}"
  else
    echo .
  fi
}
typeset -r commandDir="$(pathOfDirPartOfExecPath "$0")/"
# If $0 is a symlink, this is the invoked name, not the symlink referent name
typeset -r commandName="${0##*/}"
PATH="$commandDir:$PATH"

#===============================================================================

usage() {
    echo 1>&2 "
Usage: $progname [ -c [ -t ] ] [ -n ] [ -v ] originalFile replacementFile

If originalFile does not exist or differs from replacementFile,
replace originalFile with replacementFile; otherwise, delete replacementFile.

The -c option copies instead of moving.
The -t option preserves each file's modify time (useful only with -c)
The -n option does not modify anything and sets -v.
The -v option causes info about each file to be listed on stdout:
same     originalFile
new      originalFile
replaced originalFile

Author: Dave@Yost.com
First version: 2004-12-28
Last rev: 2015-06-07
"
    exit 2
}

zparseopts -D -K - -help=argHelp c=argCopy v=argVerbose t=argPreserveMtime n=argDryRun

if [[ $# != 2 ]] ; then
	usage
fi

if [[ $#argHelp != 0 ]] ; then
	usage
fi

case $1 in
--help) usage ;;
-*) usage "Unknown option: $1"
	;;
esac

if [[ $#argDryRun != 0 ]] ; then argVerbose=(-v) ; fi

#===============================================================================

original=$1
replacement=$2

replace=
if [[ ! -e $original ]] ; then
	if [[ $#argVerbose != 0 ]] ; then echo  "new      $original" ; fi
	replace=true
elif ! cmp $original $replacement > /dev/null ; then
	if [[ $#argVerbose != 0 ]] ; then echo  "replaced $original" ; fi
	replace=true
else
	if [[ $#argVerbose != 0 ]] ; then echo  "same     $original" ; fi
	if [[ $#argDryRun   = 0 && $#argCopy = 0 ]] ; then rm -f $replacement ; fi
fi

if [[ $#argDryRun = 0 && ! -z $replace ]] ; then
    mkdir -p $(dirname $original)
	if [[ $#argCopy != 0 ]] ; then
		if [[ $#argPreserveMtime != 0 ]] ; then pArg=-p ; else pArg= ; fi
		cp $pArg $replacement $original
	else
		mv $replacement $original
	fi
fi