#! /bin/bash -f
# Last edited on 2012-05-05 13:23:46 by stolfilocal

cmd="${0##*/}";
usage="${cmd} {FILE} {TARGET}"

# Used to ship TeX "\include" files from a work directory
# to the paper's editing directory.
# TARGET is a directory or a file name, as in "mv".
# If the target does not exist, or is different than FILE,
# copies the latter to the former, making a backup
# and printing the differences.

if [[ $# -ne 2 ]]; then
  echo "usage: ${usage}" 1>&2; exit 1
fi

locfile="$1"; shift
target="$1"; shift

name="${locfile##*/}"
targdir="${target%/*}"
# echo "locfile = ${locfile}  name = ${name}  target = ${target}  targdir = ${targdir}"

if [[ -d ${target}  ]]; then
  dir="${target}"
  remfile="${dir}/${name}"
elif [[ -d ${targdir}  ]]; then
  dir="${targdir}"
  remfile="${target}"
else
  echo "invalid target ${target}" 1>&2; exit 1
fi

tmp="/tmp/$$"

if [[ ! ( -r ${locfile} ) ]]; then
  echo "file ${locfile} does not exist" 1>&2; exit 1
fi

if [[ ! ( -d ${dir} ) ]]; then
  echo "${dir} is missing or not a directory" 1>&2; exit 1
fi

if [[ -d ${remfile} ]]; then
  echo "${remfile} is a directory" 1>&2; exit 1
fi

if [[ ! ( -r ${remfile} ) ]]; then
  # Target file does not exist:
  update=1
else
  # Target file exists:
  if cmp -s ${locfile} ${remfile}; then
    # Files are identical, do not update (preserve the modtime):
    update=0
  else
    # Files differ, show differences:
    diff -bB ${remfile} ${locfile} | head -25
    update=1
  fi
fi

if [[ ${update} -ne 0 ]]; then  
  cp -p ${locfile} ${tmp}.file && mv -vb ${tmp}.file ${remfile}
fi