#!/usr/bin/env bash

echo Configuring...

set -eu
set -o pipefail

prefix='/usr/local'

if type -path pypy > /dev/null 2>&1
then
	which_python=$(type -path pypy)
elif [ -e /usr/local/pypy-1.5/bin/pypy ]
then
	which_python=/usr/local/pypy-1.5/bin/pypy
elif type -path python > /dev/null 2>&1 && [ $(uname -s) != Darwin ]
then
	which_python=$(type -path python)
fi
use_cython=False
bindir=""

function usage
{
	retval="$1"
	(
	echo "Usage: $0"
	echo "   --prefix prefix (The prefix for the backshift install; defaults"
	echo "      to $prefix)"
	echo "   --bindir /bin/dir (The directory to put the backshift script in;"
	echo "      defaults to $prefix/bin)"
	echo "   --python /path/to/preferred/python (defaults to $which_python on"
	echo "      this system.  CPython 2, CPython 3, pypy and jython are"
	echo "      reasonable choices)"
	echo "   --use-cython (helps performance with CPython 2.x or 3.x, do not use"
	echo "      with Pypy or Jython, defaults to False.)"
	echo "   --help"
	)
	exit "$retval"
}

function correct_cwd
{
	if [ -d 'hardlink-test' ] && \
		[ -d 'tar-test' ] && \
		[ -d 'treap' ] && \
		[ -d 'tests' ] && \
		[ -d 'example-finds' ] && \
		[ -d 'doc' ]
	then
		return
	else
		echo "$0: Sorry, you must run this script from the directory containing it" 1>&2
		exit 1
	fi
}

correct_cwd

while [ "$#" -ge 1 ]
do
	case "$1" in
		--prefix)
			prefix="$2"
			shift
			;;
		--prefix=*)
			prefix=$(echo "$1" | sed 's#^--prefix=##')
			;;
		--bindir)
			bindir="$2"
			shift
			;;
		--bindir=*)
			bindir=$(echo "$1" | sed 's#^--bindir=##')
			;;
		--python)
			which_python="$2"
			shift
			;;
		'--python='*)
			python=$(echo "$1" | sed 's#^--prefix=##')
			;;
		'--use-cython')
			use_cython=True
			;;
		--help|-h)
			usage 0
			;;
		*)
			echo "$0: Illegal option: $1" 1>&2
			usage 1
			;;
	esac
	shift
done

if [ "$bindir" = "" ]
then
	bindir="$prefix"/bin
fi

if [ "$which_python" = "" ]
then
	echo "$0: --python required on this system" 1>&2
	exit 1
fi

mkdir -p 'install-variables'
echo "$prefix" > 'install-variables/prefix-file'
echo "$bindir" > 'install-variables/bindir-file'
echo "$which_python" > 'install-variables/python-file'
echo "$use_cython" > 'install-variables/use-cython-file'
egrep . install-variables/*

echo "Done configuring."