#!/usr/bin/env bash

usage() {
cat <<EOF
\`$0' configures ns_server to adapt to many kinds of systems.

Usage: $0 [OPTION]...

Configuration:
  -h, --help              display this help and exit

Installation directories:
  --prefix=PREFIX         install files in PREFIX (required)
  --couchdb-src=PATH      path to couchdb source directory (../couchdb)

EOF
}

prefix=
couchdb_src=../couchdb

for config_arg do
  case "$config_arg" in
      --help|-h)
          usage
          exit 0
          ;;
      --prefix=/*)
          prefix=${config_arg##--prefix=}
          ;;
      --prefix=*)
          echo "--prefix needs to be absolute path"
          exit 1
          ;;
      --couchdb-src=*)
          couchdb_src=${config_arg##--couchdb-src=}
          ;;
      *)
          echo "Unknown option: ${config_arg}"
          exit 1
          ;;
  esac
done

if test -z "$prefix" ; then
    usage
    echo "Error: --prefix option is required"
    exit 1
fi

if test '!' -f "$couchdb_src/src/couchdb/couch_db.hrl"; then
    echo "could not find couch_db.hrl in given couchdb-src path: $couchdb_src"
    exit 1
fi

cat <<EOF >${0%"${0##*/}"}/.configuration
prefix="$prefix"
couchdb_src="$couchdb_src"
EOF

sed -e "s|@couchdb_src_path@|${couchdb_src}/src/couchdb|g" <${0%"${0##*/}"}/rebar.config.in >${0%"${0##*/}"}/rebar.config

echo
echo "ns_server is configured and is ready to be built!"
echo "PREFIX: ${prefix}"
echo "couchdb-src: ${couchdb_src}"
echo
