#!/bin/sh -ex

# ISSUE: Verify current working directory.
if [ ! -x "tile-build" ]; then
    echo "$0: Must be run inside '$(dirname $0)'." >&2
    exit 1
fi

# Detect leading "--install".
install=
if [ "$1" = "--install" ]; then
    install=1
    shift
fi

# Useful subdirs.
TRB=${TILERA_ROOT}/bin
TRT=${TILERA_ROOT}/tile

# Verify "TILERA_ROOT".
if [ -z "${TILERA_ROOT}" -o ! -x "$TRB/tile-cc" ]; then
    echo "TILERA_ROOT must point to a valid Tilera MDE." >&2
    exit 1
fi

# Verify dependencies.
for dep in $DEPS; do
    if [ ! -f "$TRT$dep" ]; then
        echo "Missing '$TRT$dep'." >&2
        exit 1
    fi
done

# Standard cross configure tools.
# We use "CONFIG_SITE" to supply a bunch of configure variables.
# HACK: We use "F77=none" to avoid checking for fortran.
# ISSUE: Note that "STRIP" defaults to being empty for "vim".
CROSS_CONFIGURE_VARS=" \
  CONFIG_SITE=$TRT/etc/config.site \
  AR=$TRB/tile-ar \
  AS=$TRB/tile-as \
  CC=$TRB/tile-gcc \
  CXX=$TRB/tile-g++ \
  RANLIB=$TRB/tile-ranlib \
  STRIP=$TRB/tile-strip \
  F77=none \
"

# Normal cross configure args.
# ISSUE: We should probably use "--build=`.../config.guess`".
CROSS_CONFIGURE_ARGS_TILE=" \
  --build=x86_64-unknown-linux-gnu \
  --host=`$TRB/tile-cc -dumpmachine` \
  $CROSS_CONFIGURE_VARS \
"

# Hacky cross configure args.
# ISSUE: We should probably use "--build=`.../config.guess`".
# HACK: We approximate "--host=tile" as "--host=none-tilera-linux-gnu".
CROSS_CONFIGURE_ARGS_NONE=" \
  --build=x86_64-unknown-linux-gnu \
  --host=none-tilera-linux-gnu \
  $CROSS_CONFIGURE_VARS \
"

DESTDIR=`pwd -P`/tile
rm -rf $DESTDIR

./configure \
    --prefix=/usr \
    --enable-bashcomp \
    --enable-logrotate \
    --disable-static \
    $CROSS_CONFIGURE_ARGS_TILE

LANG=C make

LANG=C make -j1 install install-redhat DESTDIR=$DESTDIR
# ln -s ../sysconfig/vz-scripts $RPM_BUILD_ROOT/%{_configdir}/conf
# ln -s ../vz/vz.conf $RPM_BUILD_ROOT/etc/sysconfig/vz

# Only install if requested.
if [ -z "$install" ]; then exit 0; fi
tar -C $DESTDIR -cf - . | tar -C $TRT -xf -
