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

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
