#! /bin/sh

set -e

# When verbose, report git's stderr.  Otherwise, discard.
case $VERBOSE in
  (x) set -x
      exec 5>&2;;
  (*) exec 5>/dev/null;;
esac

me=$(basename "$0")

stderr ()
{
  local i
  for i
  do
    echo >&2 "$me: $i"
  done
}

verbose ()
{
  case $verbose:" $VERBOSE " in
    (*true:*|*" $me "*) stderr "$@";;
  esac
}

fatal ()
{
  stderr "$@"
  exit 1
}

usage ()
{
  cat <<EOF
Usage: $0 [OPTIONS...] PATTERN...

Simulate the execution of \`git ls-files' using the files that are
currently there instead of relying on the git repository if there is
none.  Contrary to \`git ls-files', when a pattern fails to match,
return the pattern itself instead of nothing.  This is useful when
running \`make check TESTS=no-yet-git-added.chk'.

If a pattern starts with '@', \`the git ls-files' will be performed
after changing directory to the directory part of the pattern.  Braces
can be used for multi-component directories.  For instance:

   @remote-dir/*.tex

or

   @{remote-package/subdir}/*.tex

with first \`cd remote-dir' or \`remote-package/subdir' first, then
query git.

Known bugs:

- Git accepts to list directories, ls-files cannot do that.  If you
  have a directory src, 'git ls-files sr' gives nothing, but
  'git ls-files src' does.  With ls-files (this program), you need to
  pass the wildcard: "ls-files src/*".  This works equally well for
  git-ls-files and ls-files.

Options:
  -h, --help         display this message and exit
  -s, --srcdir=DIR   location of the top srcdir
                     used to locate the Git repository if in use
  -v, --verbose      provide some logging information

If FORCE_FIND is defined, \`git' is not even tried, \`find' is used.
EOF
  exit 0
}

getopt ()
{
  while test $# -ne 0; do
    case $1 in
        (--*=*)
            opt=$(echo "$1" | sed -e 's/=.*//')
            val=$(echo "$1" | sed -e 's/[^=]*=//')
            shift
            set dummy "$opt" "$val" ${1+"$@"};
            shift
            ;;
    esac

    case $1 in
      (-h | --help)   usage;;
      (-s | --srcdir) srcdir=$2; shift;;
      (-v | --verbose) verbose=true;;
      (-*)  fatal "unexpected option: $1";;
      (.)  # Since git is recursive, "git ls-files ." returns
           # everything, which is what "find -name '*'" does.
           args="$args '*'";;
      (*)  args="$args '$1'";;
    esac
    shift
  done
}


: ${TMPDIR=/tmp}
tmp=${TMPDIR}/$me.$$
trap 'exit_status=$? && rm -f $tmp && exit $exit_status' 0
trap 'exit 1' 1 2 13 15

# The patterns.
args=
srcdir=.
getopt "$@"

# git ls-files with no args returns everything.
case $args in
  ('') set x '*';;
  (*)  eval "set x $args";;
esac
shift

verbose "cd $srcdir"
cd "$srcdir"

abssrcdir=$PWD

for pattern
do
  cd $abssrcdir
  # Decode the pattern.  $prefix must be empty, or end with a slash.
  case $pattern in
    (@{*}*)
      prefix=$(echo "$pattern" | perl -pe 's<^\@\{(.*?)\}.*><$1/>;')
      pattern=$(echo "$pattern" | perl -pe 's,.*\}/+,,')
      ;;
    (@*)
      prefix=$(echo "$pattern" | perl -pe 's<^\@(.*?)/.*><$1/>;')
      pattern=$(echo "$pattern" | perl -pe 's,^.*?/+,,')
      ;;
    (@*)
      prefix=
      ;;
  esac

  if test -n "$prefix"; then
    # We might try to go into a directory that does not exist.
    # For instance in the case of an optional subscription.  Then
    # return failure.
    if test ! -d "$prefix"; then
      verbose "cannot cd $prefix: no such directory"
      continue
    fi

    cd "$prefix"
  fi

  # It's not clear how to make the difference bw a globbing pattern that
  # produces nothing, and the fact that we are not in a repo.  We check
  # if we are in a repo by checking that there are files in the repo
  # here via "ls-files".
  if test "${FORCE_FIND+set}" != set \
      && git ls-files 2>&5 | grep . >/dev/null 2>&1; then
    git ls-files "$pattern" | sed -e "s!^!$prefix!" >>$tmp
  else
    # Cannot use git, let's use shell globbing.  But it must be "deep":
    # "git ls-files *.c" and "git ls-files foo/*.c" can return
    # foo/bar/baz.c.
    sep=
    find_args=
    # `find . -path foo/bar' does not find foo/bar because its full
    # name is ./foo/bar.  `find . -path ./foo/bar' does, and so does
    # `find . -path "*foo/bar"'.  Using the latter gives unexpected
    # matches (e.g., when we look for uob/*.chk, we don't want to
    # catch 1.-/uob/*.chk).  So prefix with "./".  There should not be
    # absolute path given as argument, so prepend "./" should be
    # harmless.
    find_args="$find_args $sep-path './$pattern'"
    sep=" -or "

    # Git is file-only, dirs don't exist per se.
    find_args="'(' $find_args ')' -and -not -type d"

    # And of course it does not list .git.
    find_args="$find_args -and -not -path './.git/*'"

    find="${FIND:-find} . $find_args"
    verbose "running $find"
    # Git does not prefix by "./".
    # It sorts, and does not issue duplicates.
    eval "$find" | sed -e "s,^\./,$prefix,g" | sort -u >>$tmp
  fi
done
test -s $tmp ||
  echo "$@" >$tmp

verbose "from:" $args "returning:" $(cat $tmp)
cat $tmp

exit 0
