#!/bin/zsh
# vim: sw=2 ts=2 et!
target=Makefile
arguments="$@"
typeset -A opts;
opts=(
with-debug      yes
with-extensions yes
with-lock 	    yes
with-parallel	  yes
with-cache 	    yes
with-defer 	    yes
with-completion yes
)

if [[ $1 == "--help" || $1 == "-h" ]]; then
cat >&1 <<EOH
Usage:
    ./configure --with-option[=[yes|no]] --[enable|disable]-option

Available options:

    - debug      - Enable/disable debug library
    - extensions - Enable/disable lock, parallel, cache and defer options
    - lock       - Enable/disable lock
    - parallel   - Enable/disable parallel
    - cache      - Enable/disable cache
    - defer      - Enable/disable defer
    - completion - Enable/disable completion

All options are enabled by default.

Example:

    # Disable lock, parallel, cache and defer
    ./configure --disable-extensions

    # Disable completion
    ./configure --disable-completion
    
    # Enable debug
    ./configure --with-debug

EOH
  exit 0 
fi


while [[ $# -gt 0 ]]; do
	argkey="${1%\=*}"
	key="${argkey//--/}"
  if [[ $key = enable-* || $key = disable-* ]]; then
    if [[ $1 = *=* ]]; then
      printf "No options required for: %s (%s)\n" $argkey $1 >&2
      exit 1
    fi
    [[ $key = enable-* ]] && value=yes || value=no
    key="with-${key//enable-/}"
    key="${key//disable-/}"
    if [[ ! $opts[$key] ]]; then
      printf "Invalid option argument: %s (%s)\n" $argkey $key >&2
      printf "Valid options are: %s\n" ${(kj:, :)opts} >&2
      exit 1
    fi
    
    # Disable all extentions
    if [[ $key == "with-extensions" && $value == "no" ]]; then
      opts[with-lock]=no
      opts[with-parallel]=no
      opts[with-cache]=no
      opts[with-defer]=no
    fi
  else
    if [[ $1 = *=* ]]; then
      value="${1#*=}"
    else
      value=$opts[$key]
    fi
  fi

  if [[ $opts[$key] != "" ]]; then
    opts[$key]=$value
  else
    printf "Invalid argument: %s (%s)\n" $key $1 >&2
    exit 1
  fi

  shift

done

BANNER_SEP=$(printf '%*s' 70 | tr ' ' '\#')

cat > $target <<EOM
${BANNER_SEP}
# This file was autogenerated by 'configure'. Do not edit it directly!
# Invocation was: $0 $arguments
${BANNER_SEP}
EOM

{
  for config in ${(k)opts}; do
    echo "${${config:u}//-/_}=${opts[$config]}"
  done

  echo ${BANNER_SEP}
  cat Makefile.in
} >> $target
