#!/bin/bash

function help {
  echo
  echo "makediff 0.3 -- .diff File Creation Tool
Copyright (c) 2002, 2003  Thomas Lahn <PointedEars@gmx.de>

Usage: `basename $0` [-R] PREFIX [PATH] [diff-OPTIONS]

-R              Recurse subdirectories. Not yet implemented.
PREFIX          Filename prefix to distinct file versions. Required.
                  Note that a bad prefix may result in junk files, so choose it
                  wisely and better only on directories with files that HAVE
                  a common prefix. The \`TAB' key is your friend ;-)
PATH            Directory from where to start. The default is the current
                  working directory.
diff-OPTIONS    Options for the \`diff' program. Type \`diff --help' for details.
  "
}

if [ -z "$1" ]; then
  help
  exit 0
else
  echo
  test "$1" = "-R" && shift # not yet implemented
  test -z "$1" && help && exit 0
  prefix=$1; shift
  test -n "$1" && dir=$1 && shift
  last=""
# checking for purpose-invalid diff options
  for i in "$*"; do
    if [ "$i" = "--help" ] || [ "$i" = "--version" ] || [ "$i" = "-v" ]; then
      diff --help
      echo
      exit 0
    fi
  done
# checking for ls -v
  test -n "`ls -1v 2> /dev/null`" && v="-v"
  if [ -n "$dir" ]; then
    if [ -d "$dir" ] || [ -x "$dir" ]; then
      cd "$dir"
    else
      echo "`basename $0`: Unable to access directory: $dir" >&2
      echo
      exit 1
    fi
  fi
  files=`ls $v ${prefix}* 2>&1`
  if [ $? -eq 0 ] && [ -n "$files" ]; then
    test ! -d diff && mkdir diff
    for i in $files; do
      test -n "$last" && diff -u $* $last $i > diff/$prefix`echo $last | sed 's/'$prefix'-*//'`-`echo $i | sed 's/'$prefix'-*//'`.diff
      last=$i
    done
  else
    if [ -n "$files" ]; then
      echo "`basename $0`: $files" >&2
      echo
      exit 1
    fi
  fi
  echo
fi
