#!/usr/bin/env bash

set -e

# for the beginning, we have to find real imake

if [ `uname` == 'NetBSD' ]; then
  IFS=$', \n' read -a output < <(whereis -p imake)
elif [ `uname` == 'FreeBSD' ]; then
  IFS=$', \n' read -a output < <(whereis -ba imake)
elif [ `uname` == 'Linux' ]; then
  IFS=$', \n' read -a output < <(whereis -b imake)
elif [ `uname` == 'SunOS' ]; then
  # probably won't work under Solaris 10
  IFS=$', \n' read -a output < <(whereis -b -B /usr/openwin/bin -f imake)
else
  IFS=', ' read -a output < <(whereis imake)
fi

# make sure we haven't found our wrapper instead of real imake
if [ "${output[0]}" == "$XV_WRAPPER" ] || \
   [ "${output[0]}" == './imake' ]     || \
   [ "${output[0]}" == 'imake:' ];        \
then
  if [ "${output[1]}" == "$XV_WRAPPER" ] || \
     [ "${output[1]}" == './imake' ];       \
  then
    # under GNU whereis, second output item is actually first
    IMAKE="${output[2]}"
  else
    IMAKE="${output[1]}"
  fi
else
  IMAKE="${output[0]}"
fi

if [ -z "$IMAKE" ]; then
  echo "imake not found!" 1>&2
  exit 1
fi

echo "imake-wrapper: running imake $* in directory `pwd`"

$IMAKE "$@"

if [ -f "$IMAKEAPPEND" ]; then
  cat "$IMAKEAPPEND" >> Makefile
fi

# Fix Makefile to stop after errors in subdirs (but not for "clean" targets).
# The first line is necessary for XFree86 3.x to make it stop after errors.
# The 2nd line is necessary for XFree86 4.x to make it continue after "make clean" errors
# (it sets SHELL=/bin/sh -e).
perl -p -i -e 's/(\$\(MAKE\)[^;|]*(all|depend|populate|lintlib|includes|tags)[^;|]*);/$1 || exit 1;/;
               s/(\$\(MAKE\)[^;|]*clean[^;|]*);/$1 || true;/;' Makefile

exit 0
