#!/bin/sh
src=`dirname $0`
pfx=/usr/local

oss="linux mingw"

help() {
  echo "Usage: $0 [OPTION]... [VAR=VALUE]..."
  exit 1
}

option() {
  opt=$1
  val=$2
}

if test "" = "$src"; then src="."; fi

for i in $oss; do
  if test 1 -eq `uname|grep -i $i|wc -l`; then os=$i; fi
done

if test "" = "$os"; then echo "Error: Unsupported OS."; fi

while test "$1" != ""; do
  `echo $1|sed -e 's/\(\(-\?-\?[A-Za-z0-9]\+\)\(=\(.*\)\)\?\)\|.*/option \2 \4/g'`
  shift
  case $opt in
    "--help") help ;;
    "--prefix") pfx=$val ;;
    "--bindir") bindir=$val ;;
    "--libdir") libdir=$val ;;
    "--includedir") includedir=$val ;;
	"CPPFLAGS") cppflags=$val ;;
	"LDFLAGS") ldflags=$val ;;
	"LIBS") libs=$val ;;
    *) echo "Error: Unknow option: $1."; help ;;
  esac
done

# transform relative path into absolute
src=`echo "$src"|sed -e "s,^\([^/]\),$PWD/\1,g"`
pfx=`echo "$pfx"|sed -e "s,^\([^/]\),$PWD/\1,g"`

if test "" = "$bindir"; then
  bindir=$pfx/bin
else
  bindir=`echo "$bindir"|sed -e "s,^\([^/]\),$PWD/\1,g"`
fi 

if test "" = "$libdir"; then
  libdir=$pfx/lib
else
  libdir=`echo "$libdir"|sed -e "s,^\([^/]\),$PWD/\1,g"`
fi 

if test "" = "$includedir"; then
  includedir=$pfx/include
else
  includedir=`echo "$includedir"|sed -e "s,^\([^/]\),$PWD/\1,g"`
fi 

rm -f config.mak
touch config.mak

echo "OS:=$os" >> config.mak
echo "SRC:=$src" >> config.mak
echo "PFX:=$pfx" >> config.mak
echo "BINDIR:=$bindir" >> config.mak
echo "LIBDIR:=$libdir" >> config.mak
echo "INCLUDEDIR:=$includedir" >> config.mak
if test "" != "$cppflags"; then echo "CPPFLAGS+=$cppflags" >> config.mak; fi
if test "" != "$ldflags"; then echo "LDFLAGS+=$ldflags" >> config.mak; fi
if test "" != "$libs"; then echo "LDLIBS+=$libs" >> config.mak; fi

if test ! . -ef $src; then
  cp -p $src/Makefile .
fi
