#!/bin/sh

# 2014-03-05:  Added the --keep-newer-files option.
# 2007-12-03:  Handle spaces in the filenames in the tar files.
# 2007-11-28:  Allow multiple files
# 2006-08-04:  Changed to remove temp diretory with -f option so it won't
#              prompt on read-only files.

if [ $# = 0 ]; then
  echo >&2
  echo "Usage: untar [--keep-newer-files] <tar file> [<tar file> ...]" >&2
  echo >&2
  echo "Options:" >&2
  echo >&2
  echo "  --keep-newer-files" >&2
  echo >&2
  echo "    Only overwrites local existing files if the archived " >&2
  echo "    copies are newer.  The user will not be prompted as to " >&2
  echo "    whether or not the file should be overwritten when this " >&2
  echo "    option is used." >&2
  echo >&2
  echo "Description:" >&2
  echo >&2
  echo "  Extracts the given tar file to the current directory." >&2
  echo "  If the tar file contains a file that already exists " >&2
  echo "  and it is different from the current file, then it " >&2
  echo "  prompts whether or not to overwrite." >&2
  echo >&2
  exit 1
fi

full_path_name() {  # must be an easier way to do this
  local cwd=`pwd`
  local dn=`dirname $1`
  cd $dn
  local dir=`pwd`
  cd $cwd
  echo $dir/`basename $1`
}

keep_newer_files_op=""

if [ $1 = "--keep-newer-files" ]; then
  keep_newer_files_op=$1
  shift
fi

cwd=`/bin/pwd`
tempdir=$cwd/untar_temp.$$
mkdir "$tempdir" || exit 1
trap "rm -rf $tempdir" EXIT
for tarfile in $*;do
  tarfile=`full_path_name "$tarfile"`
  uncompress_op=""
  if [ x`basename $tarfile .gz` != x`basename $tarfile` ]; then
    uncompress_op="-z"
  fi

  cd "$tempdir"
  tar x $uncompress_op -kf "$tarfile"
  find -print | while read file;do
    file=${file#./}
    oldpath=$cwd/$file
    newpath=$tempdir/$file
    if [ -d "$newpath" ]; then
      if [ ! -d "$oldpath" ]; then
        mkdir "$oldpath"
      fi
    else
      if [ ! -f "$oldpath" ]; then
        mv "$newpath" "$oldpath"
        echo "$file"
      else
        if cmp -s "$oldpath" "$newpath"; then
          echo "$file (already exists)"
        else
          echo "${file#./} is different."
          if [ "$newpath" -nt "$oldpath" ]; then
	    if [ "$keep_newer_files_op" != "" ]; then
	      echo "The archived file is newer, overwriting"
	      mv "$newpath" "$oldpath" </dev/tty
	    else
	      echo "The archived file is newer"
	      mv -i "$newpath" "$oldpath" </dev/tty
	    fi
          else
	    if [ "$keep_newer_files_op" != "" ]; then
	      echo "The local file is newer, not overwriting"
	    else
	      echo "The local file is newer"
	      mv -i "$newpath" "$oldpath" </dev/tty
	    fi
          fi
        fi
      fi
    fi
  done
  cd "$cwd"
done
