#! /bin/sh
#This is a crappy hack
#better to use first arg check
if ! test -f /tmp/.sh; then
  touch /tmp/.sh
  bash $0 ${1+"$@"}
  rm /tmp/.sh
  exit 0
fi


# Awk out the version from source
AWK="`which awk`"
if test -z "${AWK}"; then
 AWK="`which gawk`"
fi

ver="?.?.?"
ver=`grep "char" src/main.c | $AWK '/egg_version/ {print $5}' | sed -e 's/\"//g' | sed -e 's/\;//g'`
numver=`grep "int" src/main.c | $AWK '/egg_numver =/ {print $5}' |  sed -e 's/\;//g'`
PACKNAME=`grep "PACKNAME " pack/pack.cfg | $AWK '/PACKNAME/ {print $2}'`
BUILDTS=`cat src/build.h | $AWK '{print $3}'`
builddate=`perl -e "use POSIX 'strftime';print strftime(\"%m.%d.%Y\n\",gmtime(${BUILDTS}));"`

clear
#Display a banner
bt=`grep -A 3 "char \*wbanner() {" src/misc.c | grep "switch" | sed -e "s/.*switch (r % \(.\)) {/\1/"`
if test -f /proc/self/stat; then
  bn=$[(`cat /proc/self/stat | $AWK '{print $1}'` % ${bt})]
else
  bn=$[(`date +%s` % ${bt})]
fi
banner=`grep -A 15 "char \*wbanner() {" src/misc.c | grep "case ${bn}:" | sed -e "s/.*case ${bn}: return STR(\"\(.*\)\");/\1/"`
echo -e "${banner}"
echo -e "Version:   ${ver}\nBuild:     ${builddate}"
echo -e `grep -r "http://" src/misc.c | sed -e "s/dprintf(idx, STR(\"\(.*\)\"));/\1/"`
echo

usage() 
{
    echo "Usage: $0 [-bcdn] [-t dir] [-T] [all|hub|leaf]"
    echo
    echo "    The options are as follows:"
    echo "    -b        Use bzip2 instead of gzip when packaging."
    echo "    -c        Cleans up old binaries/files before compile."
    echo "    -d        Builds a debug package."
    echo "    -n        Do not package the binaries."
    echo "    -t dir    Where to search for TCL libraries."
    echo "    -T        Builds TCL if it is not on the system."
}

debug=0
all=0
hub=0
leaf=0
clean=0
type=
tcldir=
buildtcl=0
nopkg=0
bzip=0

while getopts t:bcdhnT opt ; do
        case "$opt" in
        b) bzip=1 ;;
	c) clean=1 ;;
        d) debug=1 ;;
	h) usage; exit 0 ;;
        n) nopkg=1 ;;
	t) tcldir="$OPTARG" ;;
	T) buildtcl=1 ;;
        *) usage; exit 1 ;;

        esac
done

shift $(($OPTIND - 1))

if [ $buildtcl = "1" ]; then
 echo "Hold tight"
 misc/maketcl
 rm -rf tcl8.4.4*
 echo "Done. (You must run ./build again with normal parameters)"
 exit 0
fi

if test -z "$1"; then
 usage
 exit 1
else
 if [ $1 = "all" ]; then
  all=1
 elif [ $1 = "leaf" ]; then
  leaf=1
  type="leaf"
 elif [ $1 = "hub" ]; then
  hub=1
  type="hub"
 else
  all=1
 fi
fi

if [ $debug = "1" ]; then
 d="d"
else
 d=""
fi

if [ $all = "1" ]; then
 type="all"
 leaf=1
 hub=1
fi

# FIXME: We need to check for the proper pack/ files no? 

# Figure what bins we're making
case `uname` in
  Linux) os=Linux;;
  FreeBSD) case `uname -r` in
    5*) os=FreeBSD5;;
    4*) os=FreeBSD4;;
    3*) os=FreeBSD3;;
  esac;;
  OpenBSD) os=OpenBSD;;
esac

if test -z $os
then
  echo "[!] Automated packaging disabled, `uname` isn't recognized"
fi

echo "[*] Building ${PACKNAME}::${type} for $os"

# Run ./configure, then verify it's ok
echo "[*] Configuring..."
umask 077 >/dev/null

if test -z "$tcldir"; then
  echo "[*] Searching for TCL in default paths (use '-t dir' to change)"
  ./configure --silent 
else
  echo "[*] Searching for TCL in: $tcldir"
  ./configure --silent --with-tcllib=${tcldir}/lib/libtcl8.4.a --with-tclinc=${tcldir}/include/tcl.h
fi


MAKE="`which gmake`"
if test -z "${MAKE}"; then
 MAKE="`which make`"
fi


if [ $clean = "1" ]; then
 echo "[*] Cleaning up old binaries/files..."
 ${MAKE} clean > /dev/null
fi

_build()
{
 if [ $[${tb}] = "1" ]; then
  echo "[*] Building ${d}${tb}..."
  ${MAKE} ${d}${tb}
  if ! test -f ${tb}; then
    echo "[!] ${d}${tb} build failed"
    exit 1
  fi
 fi
}

if [ -f stamp.hub ]; then
 tb="hub"
 _build
 tb="leaf"
else
 tb="leaf"
 _build
 tb="hub"
fi
_build


if [ $all = "1" ]; then
 fls="leaf hub"
elif [ $leaf = "1" ]; then
 fls="leaf"
elif [ $hub = "1" ]; then
 fls="hub"
fi

if test -n "$d"; then
 d="-debug"
fi

for bin in $fls
do
  mv -f $bin $bin.$os.$numver${d}
done

# Wrap it nicely up into an archive
if [ $nopkg = "0" ]; then
  echo "[*] Packaging..."
  if [ $bzip = "1" ]; then
    zip="j"
    ext="bz2"
  else
    zip="z"
    ext="gz"
  fi
  #This MALLOC business is to not Abort 'tar' due to some bug it has.
  tmp=${MALLOC_CHECK_}
  unset MALLOC_CHECK_
  tar -c${zip}f ${PACKNAME}.$os.$numver${d}.tar.${ext} *.$os.$numver${d}
  if test -n "$tmp"; then
    declare -x MALLOC_CHECK_=$tmp
  fi
  rm -f *$os.$numver${d}
  echo "Binaries are now in '${PACKNAME}.$os.$numver${d}.tar.${ext}'."
fi
  exit 0

