#!/bin/sh
# Helper for saving time when recompiling, skipping files that haven't
# changed in a meaningful way (e.g. if you only change a comment...)
#
# LGPL v2, David Faure <david@mandrakesoft.com>

usage()
{
  echo "Usage:"
  echo " $0 hidechange file    Hides the fact that file was changed (use with care!)"
  echo " $0 show               Lists what make currently has to rebuild"
  echo " $0 why file           Explains why make must rebuild file"
  exit 1;
}

if [ $# -eq 0 ]; then usage; fi
CDPATH=
builddir=$PWD

# 'srcdir != builddir' stuff
if test ! -f Makefile && test -n "$OBJ_SUBDIR"; then
  builddir=$OBJ_SUBDIR
else
  if test ! -f Makefile && test -n "$OBJ_REPLACEMENT"; then
     builddir=`pwd | sed -e "$OBJ_REPLACEMENT"`
  fi
fi

if test ! -f Makefile && test -n "$OBJ_SUBDIR"; then
   builddir=$OBJ_SUBDIR
fi
cd $builddir
srcdir=`egrep '^srcdir *=' Makefile | sed -e "s#srcdir *= *##"`
UNSERMAKE=`type -p unsermake`
using_unsermake=
if head -n 1 Makefile | grep unsermake >/dev/null; then
    using_unsermake=new
fi
if head -n 1 Makefile | grep automake >/dev/null; then
    using_unsermake=old
fi


case $1 in
  hidechange )
    if [ $# -ne 2 ]; then usage; fi
    ## TODO: unsermake support (or support in unsermake itself)
    deps=`make SUBDIRS='' -n | grep '\-o' | sed -e 's/.*-o \([^ ]*\).*/\1/'`;
    if [ -n "$deps" ]; then
      oldestdep=`ls -t $deps 2>/dev/null | tail -1`
      thefile=$2
      if [ -f $srcdir/$thefile ]; then
          thefile=$srcdir/$thefile
      fi
      echo
      echo "Setting date of $thefile back in time with:"
      echo "touch -r $oldestdep $thefile" ; touch -r $oldestdep $thefile
    fi
    ;;
  show )
    if [ $# -ne 1 ]; then usage; fi
    if test "$using_unsermake" != "new"; then
      # Look at the commands that make will issue, and extract "-o output".
      # The only trouble, with libtool, is that this gives us .libs/foo.o instead of foo.lo
      make SUBDIRS='' -n | grep '\-o' | sed -e 's/.*-o \([^ ]*\).*/\1/'
    else
      # Solve the above problem (when using new-unsermake) by watching the "echo" lines for creating .lo files
      # separately from the rest of the "-o target" lines (for libs and binaries)
      # (For libs and bins another way would be to grep for "linking")
      # The "ls" is for sorting by date
      $UNSERMAKE -n | perl -e 'while(<>) { if (/by libtool/) { s/.*> //; print; } if (m/-o ([^ ]*)/ && $1!~/\.o$/) { print "$1\n"; } }' | xargs --no-run-if-empty ls -t -1
    fi
    ;;
  why )
    if [ $# -ne 2 ]; then usage; fi
    ## TODO: unsermake support (or support in unsermake itself)
    make SUBDIRS='' -n -d $2 | egrep -e "(newer than target \`$2'|Must)"
    ;;
  * ) usage ;;
esac
