#! /bin/sh

PKG_ARCH=`cat debian-arch`

# Assume the examples are in the current working directory.
exampledir=`pwd`
test -d tiny || {
  echo "$0: you need to be in the example directory to run this." 1>&2
  exit 1
}

# options to pass to configure.
configure_options='--enable-maintainer-mode'

# output directory...
outputdir=`pwd`/"example-output"
test -d "$outputdir" || mkdir -p "$outputdir" || {
  echo "$0: could not make output-directory $outputdir" 1>&2
  exit 1
}
# pkgwrite configuration
pkgwrite="$exampledir/../scripts/pkgwrite"
pkgwrite_flags="--arch=$PKG_ARCH --output=$outputdir"

# distro formats to support.
if test "x$FORMATS" = x ; then
  formats="redhat debian"
else
  formats="$FORMATS"
fi

# known examples
if test "x$EXAMPLES" = x ; then
  examples='tiny/aa tiny/bb tiny/cc tiny/dd tiny/ee tiny/ll'
else
  examples="$EXAMPLES"
fi

for example in $examples ; do
  failed=0
  cd $exampledir/$example

  # make a command to cat the config.status file.
  # XXX: support forcible rebuild.
  if test -r "./config.status" ; then
    ./config.status > /dev/null 2>&1
  else
    ./bootstrap > /dev/null 2>&1 || failed=1
    if test $failed = 0 ; then
      ./configure $configure_options > /dev/null 2>&1 || failed=1
    fi
  fi

  if test $failed = 0 ; then
    # figure out test_package and test_version.
    catconf="cat config.status"
    test_package=`$catconf | sed -n -e 's,s%@PACKAGE@%\\(.*\\)%g,\\1,p'`
    test_version=`$catconf | sed -n -e 's,s%@VERSION@%\\(.*\\)%g,\\1,p'`

    llogfile="$outputdir/$test_package-$test_version.log"
    echo "(logging to $llogfile)" 1>&2

    # Build the makefile, if necessary.
    test -r Makefile || {
      if test -r configure ; then
	./configure $configure_options || failed=1
      else
	if test -f "bootstrap" && test -x "bootstrap" ; then
	  ./bootstrap >> $llogfile 2>&1 || failed=1
	  ./configure $configure_options >> $llogfile 2>&1 || failed=1
	elif test -f "autogen.sh" && test -x "autogen.sh" ; then
	  ./autogen.sh $configure_options >> $llogfile 2>&1 || failed=1
	else
	  echo "$exampledir:" \
	       "malformed example (no autogen.sh nor bootstrap)" 1>&2
	  failed=1
	fi
      fi
    }
  fi
  test $failed = 1 || test -r Makefile || failed=1
  if test $failed = 0 ; then
    make dist >> $llogfile 2>&1 || failed=1
  fi
  cd $exampledir
  tarball="$example/$test_package-$test_version.tar.gz"
  for format in $formats ; do
    test "$failed" = 1 && break
    logfile="$outputdir/$test_package-$test_version--$format.log"
    echo "(logging to $logfile)" 1>&2
    if test $failed = 0 ; then
      flags="$pkgwrite_flags --tarball=$tarball --format=$format"
      echo "running: $pkgwrite $flags" 1>&2
      $pkgwrite $flags > "$logfile" 2>&1 || failed=1
    else
      break
    fi
  done
  if test $failed = 1 ; then
    failed_packages="$failed_packages $example"
  fi
done

test "x$failed_packages" = x || {
  echo "The following packages did not build:$failed_packages." 1>&2
  exit 1
}

exit 0
