#! /bin/sh
if [ -x /bin/true ]; then TRUE=/bin/true;
elif [ -x /usr/bin/true ]; then TRUE=/usr/bin/true;
elif command -v true &> /dev/null; then TRUE=true;
else echo "Can't find /bin/true or /usr/bin/true and no true command" ; exit 1;
fi

while ${TRUE} ; do
  mkdirs=0
  ifdiff=0
  
  while [ $# -ge 0 ] ; do
    case $1 in
      -d) mkdirs=1 ;;
      -o) shift; owner=$1 ;;
      -g) shift; group=$1 ;;
      -m) shift; mode=$1 ;;
      --ifdiff) ifdiff=1 ;;
      -*) break 2 ;;
      *) break ;;
    esac
    shift
  done
  
  if [ $mkdirs -eq 1 ] && [ $ifdiff -eq 1 ] ; then
    break
  fi

  if [ $mkdirs -eq 1 ] ; then
    dirs=$*
  
    for dir in $dirs ; do
      stack=""
      while [ "$dir" != "/" -a "$dir" != "." -a "$dir" != ".." ] ; do
        stack="$dir $stack"
        dir=`dirname $dir`
      done

      for dir in $stack ; do
        if [ ! -d $dir ] ; then
          if mkdir $dir ; then
            if [ "$owner" != "" ] ; then chown $owner $dir ; fi
            if [ "$group" != "" ] ; then chgrp $group $dir ; fi
            if [ "$mode" != "" ] ; then chmod $mode $dir ; fi
          fi
        fi
      done
    done
  else
    nargs=$#
    if [ $nargs -lt 2 ] ; then break ; fi
    
    files=""
    while [ $# -ne 1 ] ; do
      files="$files $1"
      shift
    done
    dest=$1
    
    if [ ! -d $dest -a $nargs -ne 2 ] ; then break ; fi
  
    for file in $files ; do
      destfile=$dest
      if [ -d $destfile ] ; then destfile=$destfile/`basename $file` ; fi
      if [ $ifdiff -eq 1 ] && cmp -s $file $destfile || cp -f -p $file $destfile ; then
        if [ "$owner" != "" ] ; then chown $owner $destfile ; fi
        if [ "$group" != "" ] ; then chgrp $group $destfile ; fi
        if [ "$mode" != "" ] ; then chmod $mode $destfile ; fi
      fi
    done
  fi
  
  exit 0
done

echo "usage: $0 [ -o owner] [ -g group ] [ -m mode ] [ --ifdiff] file dest"
echo "       $0 [ -o owner] [ -g group ] [ -m mode ] [ --ifdiff] file file ... dir"
echo "       $0 -d [ -o owner] [ -g group ] [ -m mode ] dir dir ..."
exit 1
