#!/bin/bash
for v in "$@"
do
    if [ $v == "-bytecode" ]; then
	BYTECODE="1"
    else
	if [ ${v:0:12} == "-qeditasdir=" ]; then
            INSTALLDIR=${v:12}
	    if [ ! -d $INSTALLDIR ]; then
		echo "$INSTALLDIR is not a directory"
	    fi
	else
	    if [ ${v:0:9} == "-datadir=" ]; then
		DATADIR=${v:9}
	    else
		echo "Unknown command line argument $v"
		echo "configure can be given the following arguments:"
		echo "-bytecode (to only build bytecode)"
		echo "-qeditasdir=<dir> (to specify the install directory)"
		echo "-datadir=<dir> (to specify the default directory for Qeditas data)"
		exit 1
	    fi
	fi
    fi
done
if [ ! $DATADIR ]; then
    DATADIR=$HOME/.qeditas
fi
if [ ! -d $DATADIR ]; then
  mkdir $DATADIR
fi
if [ ! -d $DATADIR/testnet ]; then
  mkdir $DATADIR/testnet
fi
echo let datadir = ref \"$DATADIR\" > src/config.ml
echo let testnet = ref false >> src/config.ml
echo let staking = ref false >> src/config.ml
echo let ip = ref None >> src/config.ml
echo let ipv6 = ref false >> src/config.ml
echo let port = ref 20805 >> src/config.ml
echo let socks = ref None >> src/config.ml
echo let socksport = ref 9050 >> src/config.ml
echo let maxconns = ref 200 >> src/config.ml
echo let seed = ref \"\" >> src/config.ml
echo let lastcheckpoint = ref \"\" >> src/config.ml
echo let currledgerroot = ref \"a47da9044687cc40e368fbd60f404ad5b4ddd4cf\" >> src/config.ml
echo let qednetdexec = ref \"$HOME/qednet/src/qednetd\" >> src/config.ml
echo let ctreedatadir = ref \"/tmp/deprecated\" >> src/config.ml
echo let chaindatadir = ref \"/tmp/deprecated\" >> src/config.ml
echo let prompt = ref \"\> \" >> src/config.ml
if [ $BYTECODE ]; then
    if [ $INSTALLDIR ]; then
	echo "bytecode cannot be installed"
	echo "configure failed"
	exit 1
    fi
fi
OCAMLC=`which ocamlc`
if [ -z $OCAMLC ]; then
    echo 'Could not find ocamlc'
    echo 'configure failed'
    exit 1
fi
echo OCAMLC=$OCAMLC > Makefile
if [ $BYTECODE ]; then
    echo 'all: bytecode' >> Makefile
else
    OCAMLOPT=`which ocamlopt`
    if [ -z $OCAMLOPT ]; then
	echo 'Could not find ocamlopt'
	echo 'Only the bytecode will be created'
	BYTECODE=1
	INSTALLDIR=""
	echo 'all: bytecode' >> Makefile
    else
	echo OCAMLOPT=$OCAMLOPT >> Makefile
	echo 'all: opt' >> Makefile
    fi
fi
cat Makefile.in >> Makefile
if [ -z $INSTALLDIR ]; then
    if [ -d /usr/local/bin ]; then
	INSTALLDIR="/usr/local/bin"
    else
	if [ -d /usr/bin ]; then
	    INSTALLDIR="/usr/bin"
	else
	    echo 'No installation directory could be determined'
	    echo 'make install cannot be run'
	    echo 'To resolve this give -qeditasdir=<dir> as an argument to configure.'
	fi
    fi
fi
if [ -n $INSTALLDIR ]; then
    echo INSTALLDIR=$INSTALLDIR >> Makefile
    echo '' >> Makefile
    echo 'install:' >> Makefile
    echo -e '\tcp bin/qeditas $(INSTALLDIR)' >> Makefile
fi
