#!/bin/sh

set -e

ZWACONF=./.zwaconf

TARGET=
SRCDIR=$ZWA_WORK_DIR/libzorpll

get_version(){
  if [ -f $SRCDIR/debian/changelog ];then
      head -1 $SRCDIR/debian/changelog | sed -e 's/.*(\([^)]*\)).*/\1/'
  else
      head $SRCDIR/VERSION
  fi
}

sed_file() {

    while [ -n "$1" ]; do
        in=$1.in
        out=$1

        sed \
            -e "s/@VERSION@/${VERSION}/g" \
            $in > $out
        shift
    done
}

if [ -f $ZWACONF ]; then
  . $ZWACONF
fi

if [ -z "$TARGET" ]; then
  TARGET=$PWD/out
fi

if [ -z "$MAKE" ];then
  MAKE=make
fi

cmd=$1
shift
case "$cmd" in
  get-version)
    get_version
    ;;
  prepare-dist)
    VERSION=`get_version`
    if [ -n "$SNAPSHOT_VERSION" ]; then
      unset SNAPSHOT_VERSION
    fi
    ./configure
    make dist
    ;;
  dist-exclude-list|build-exclude-list)
    echo "out obj *.aqt *.ncb *.suo *.vcproj.*.user config.h"
    ;;
  bootstrap)
    ./autogen.sh
    ;;
  configure)

    CONFOPTS=
    while true ; do
      _arg=$1

      if [ -z "$_arg" ]; then
        break
      fi
      if [ "$_arg" = '--' ]; then
        shift
        break
      fi
      case $1 in
        --prefix*)
          _arg=${_arg##*=}
          if [ "$_arg" = "$1" ]; then
            shift
            TARGET="$1"
          else
            TARGET=$_arg
          fi
          ;;
        --enable*|--disable*|--with*)
          CONFOPTS="$CONFOPTS $1"
          ;;
        *)
          CONFOPTS="$CONFOPTS $1"
          ;;
      esac
      shift
    done
    CONFOPTS="$CONFOPTS $*"
    echo "TARGET=$TARGET" > $ZWACONF
    if [ -n "$ZBS_ARCH" ] && [ "$ZBS_ARCH" = "i386" ];then
      CONFOPTS=--build=$ZBS_ARCH-unknown-`uname | tr '[A-Z]' '[a-z]'`-gnu
    fi

    if echo $DEB_BUILD_OPTIONS | grep -q debug; then
      CONFOPTS="$CONFOPTS --enable-debug --enable-trace"
    fi

    if echo $DEB_BUILD_OPTIONS | grep -q trace; then
      CONFOPTS="$CONFOPTS --enable-mem-trace"
    fi

    ./configure --prefix $TARGET $CONFOPTS
    ;;
  make)
    case $1 in
      distclean)
        $MAKE distclean
        ;;
      *) $MAKE $@ ;;
    esac
    ;;
  *)
    echo "Unknown command: $cmd"
    exit 1
    ;;
esac
exit 0

# vim: ts=2 sw=2 expandtab
