#! /bin/sh
#
# Copyright (C) 2002, Earnie Boyd <earnie@users.sf.net>
# Copyright (C) 2007, Cesar Strauss <cestrauss@gmail.com>
#
# Based on the msysrlsbld script, part of msysDVLPR
#   http://www.mingw.org/MinGWiki/index.php/MSYSBuildEnvironment
# Inspired on ideas from cygport, part of Cygwin.

# The following src_* functions can be overrided in package-specific
# msysrlsbld.ini files.

src_build()
{
  do_build
}

src_prep()
{
  do_prep
}

src_configure()
{
  do_configure
}

src_compile()
{
  do_compile
}

src_install()
{
  do_install
}

#
# Configure, make, make install
#
do_build()
{
  src_prep || fail
  src_configure || fail
  src_compile || fail
  src_install || fail
}

# Prepare the source and build directories
do_prep()
{
  mkdir build && cd build || fail
  if [ -z "$srcdir" ]
  then
    srcdir=source
  fi
  srcdir=../$srcdir
}

# Configure the build system
#
# configure_opt are the default options for the configure script and
# can be set in a package-specific msysrlsbld.ini file.
#
do_configure()
{
  if [ -z "$configure_opt" ]
  then
    configure_opt="--prefix=/usr --disable-nls"
  fi
  $srcdir/configure $configure_opt
}

# Compile the sources
#
# ccflags can be set externally to control use of new flags without needing to
# change this file. E.G.: ccflags='-O0 -g -fnative-struct -fgnu-linker'.
#
# ccflags_extra are package-specific flags for the compiler.
#
# compile_opt are package-specific flags for the make build tool.
#
do_compile()
{
  if [ -z "$ccflags" ]
  then
    ccflags='-O2 -s -fnative-struct -fgnu-linker -finline-functions'
  fi
  make clean
  make CFLAGS="$ccflags $ccflags_extra -mcpu=pentium" CXXFLAGS="$ccflags $ccflags_extra -mcpu=pentium" $compile_opt
}

# Install in a staging area
#
# You can set msysinstalldir in your msysrlsbld.pref file so that the build
# installs to the project store directory.
# E.G.: msysinstalldir=/prj/msys/nstl.
#
# install_opt are package-specific flags for the make build tool.
#
do_install()
{
  if [ -z "$msysinstalldir" ]
  then
    msysinstalldir=`cd .. && pwd`/nstl
  fi
  make install prefix=$msysinstalldir $install_opt
  rm -f $msysinstalldir/info/dir
}

fail()
{
  echo
  echo "============="
  echo "Build failed."
  echo "============="
  exit 1
}

succeed()
{
  echo
  echo "================"
  echo "Build succeeded."
  echo "================"
}

# Read the package-specific build instructions.
#
if [ -f msysrlsbld.ini ]
then
  source ./msysrlsbld.ini
fi

# Read the system-wide preferences
#
if [ -f /etc/msysrlsbld.pref ]
then
  source /etc/msysrlsbld.pref
fi

# Read the user-specific preferences
#
if [ -f ${HOME}/msysrlsbld.pref ]
then
  source ${HOME}/msysrlsbld.pref
fi

if src_build; then
  succeed
else
  fail
fi

