#!/bin/bash
if [ $# -lt 3 ] ; then
  echo 
  echo " 	Search svn revs for a rev that works"
  echo
  echo "	usage: search-svn-revs start-rev end-rev run [ test ]"
  echo
  echo "	'start-rev' and 'end-rev' are svn revision numbers"
  echo "	'run' is the script to run"
  echo "	'test' is the script to test for (\$? == 0) success."
  echo "	       if 'test' argument is not present, then the status from"
  echo "	       'run' argument is used for success / fail."
  echo
  echo "    Note: The binary search algorithm can produce incorrect results if the range of"
  echo "    revisions contains more complex situations than: fail fail ... succeed suceed ..."
  echo
  exit 1
fi

highest_fail=$1
lowest_succeed=$2

export GS_LIB=$GS_LIB:./lib:/home/regression/fonts

while [ $(( $highest_fail + 1 )) -lt $lowest_succeed ]; do 
  test_rev=$(( ( ( $lowest_succeed - $highest_fail ) / 2 ) + $highest_fail ))

  echo -e "checking rev: $test_rev. svn checkout ...\c"
  svn export -q -r$test_rev svn+ssh://svn.ghostscript.com/svn/ghostscript/trunk/gs gs.$test_rev > /dev/null 2>&1
  cd gs.$test_rev
  echo -e "\b\b\bdone. autogen ...\c"
  ./autogen.sh > /dev/null 2>&1
  echo -e "\b\b\bdone. make ...\c"
  make > /dev/null 2>&1
  status=$?
  if [ $status -ne 0 ] ; then
    echo -e "\b\b\bfailed."
  else
    if [ -f bin/gs ] ; then
      echo -e "\b\b\bdone. run ...\c"
      $3 > test.log 2>&1
      status=$?
      echo -e "\b\b\bdone, status=$status.\c"
      if [ $# -gt 3 ] ; then
	echo -e "test ...\c"
	$4
	status=$?
	echo -e "\b\b\bdone, status=$status.\c"
      fi
    fi
  fi
  echo
  cd ..
  rm -fr gs.$test_rev
  if [ $status -ne 0 ] ; then
    highest_fail=$test_rev
  else
    lowest_succeed=$test_rev
  fi
done
echo -e "\nFirst rev that succeeds is: $lowest_succeed"
