#!/bin/bash
#
# Build script for <PACKAGE>
#
# This build script is meant to be executed from within the source directory
# created by extracting the tarball.
#
# It will create 6 log files in the $HOME directory:
#   configure.log: All messages output during configure
#   configure.err: Just the errors output during configure
#   make.log: All messages output during make
#   make.err: Just the errors output during make
#   install.log: All messages output during make install
#   install.err: Just the errors output during make install
#
# After running the script you should check the *.err files to see
# if any problems have occurred. If that is the case, use the corresponding
# *.log files to see the error messages in context.

# Note: the ":;" before the "}" in *_commands() is a no-op that makes sure 
# that the function remains syntactically valid, even if you remove its
# contents (e.g. remove the "configure" line, because there's nothing to 
# configure for the package).

FCONFIG=0
FMAKE=0
FCHECK=1
FINSTALL=0

show_usage()
{
  echo "usage $1 [-hcimt] [-h -c -i -m -t]"
  echo ""
  echo -e "\t-h\thelp - show this message."
  echo -e "\t-c\tskip configuration."
  echo -e "\t-i\tskip installation."
  echo -e "\t-m\tskip make."
  echo -e "\t-t\tskip check / tests."
}

check_parameters()
{
  while getopts "hcimt" FLAG
  do
    case $FLAG in
      c) FCONFIG=1
        ;;
      i) FINSTALL=1
        ;;
      m) FMAKE=1
        ;;
      t) FCHECK=1
        ;;
      *) show_usage $0 
    	 exit
    	;;
    esac
  done
}

configure_commands()
{ :
  ./configure --sysconfdir=/etc --disable-nls
  # user package - no overwriting coreutils files
  # i think this is handled in patches, but BSTS
  # sed -i 's/groups.1//' man/Makefile
  # sed -i '/^bin_PROGRAMS/s/groups//' src/Makefile
}

make_commands()
{ :
  make 
}

check_commands()
{ :
  #make check
}

install_commands()
{ :
  make install && \ 
  mv -v /usr/bin/passwd /bin
}


test_pipe()
{
  for i in "${PIPESTATUS[@]}" 
  do
    test $i != 0 && { echo FAILED! ; exit 1 ; }
  done
  echo successful!
  return 0
}

check_parameters $*

# NOTE: Simply using && instead of test_pipe would not work, because &&
# only tests the exit status of the last command in the pipe, which is tee.

if [ ${FCONFIG} -eq 0 ];# || return 0
then
    echo -n Configuring...
    { configure_commands 3>&1 1>&2 2>&3 | tee "$HOME/configure.err" ;} &>"$HOME/configure.log"
    test_pipe
fi

if [ ${FMAKE} -eq 0 ];# || return 0
then
    echo -n Building...
    { make_commands 3>&1 1>&2 2>&3 | tee "$HOME/make.err" ;} &>"$HOME/make.log"
    test_pipe
fi

if [ ${FCHECK} -eq 0 ];# || return 0
then
    echo -n Checking...
    { check_commands 3>&1 1>&2 2>&3 | tee "$HOME/check.err" ;} &>"$HOME/check.log"
    test_pipe
fi

if [ ${FINSTALL} -eq 0 ];# || return 0
then
    echo -n Installing...
    { install_commands 3>&1 1>&2 2>&3 | tee "$HOME/install.err" ;} &>"$HOME/install.log"
    test_pipe
fi
