#!/bin/sh -eu

_help(){
	cat <<EOF
USAGE: gen-haproxy-conf.sh waf|no-waf proxy|no-proxy

Generate a DD-compatible HAProxy configuration to stdout.

  - The first argument indicates whether or not WAF will be enabled.
    waf: enable WAF
    no-waf: do not use WAF
  - The second argument indicates whether or not the PROXY protocol will
    be enabled on ports 8888 (HTTP) and 561 (HTTPS) for the outer layer
    (either with WAF or without).
EOF
}

case "${1:-}" in
	[wW][aA][fF])
		USE_WAF="YES"
		;;
	[nN][oO]-[wW][aA][fF])
		;;
	*)
		_help >> /dev/stderr
		exit 1
		;;
esac

case "${2:-}" in
	[pP][rR][oO][xX][yY])
		USE_PROXY="YES"
		;;
	[nN][oO]-[pP][rR][oO][xX][yY])
		;;
	*)
		_help >> /dev/stderr
		exit 1
		;;
esac

PARTS_DIR="haproxy.cnf.parts"

_binds(){
	cat "${PARTS_DIR}/bind-direct.cnf"
	if [ -n "${USE_PROXY:-}" ]; then
		cat "${PARTS_DIR}/bind-proxy.cnf"
	fi
}

# Beginning
cat "${PARTS_DIR}/head.cnf"

if [ -n "${USE_WAF:-}" ]; then
	# WAF bits
	cat "${PARTS_DIR}/defaults-waf.cnf"
	cat "${PARTS_DIR}/head-waf.cnf"
	_binds
	cat "${PARTS_DIR}/tail-waf.cnf"
	cat "${PARTS_DIR}/web-head.cnf"
else
	# Non-WAF bits
	cat "${PARTS_DIR}/defaults-non-waf.cnf"
	cat "${PARTS_DIR}/tail-non-waf.cnf"
	cat "${PARTS_DIR}/web-head.cnf"
	_binds
fi

# bk_web ending
cat "${PARTS_DIR}/web-tail.cnf"

# Application backends
cat "${PARTS_DIR}/backends.cnf"
