#!/usr/bin/env bash
set -e

script=$(basename "$0")
version="1.0.1"

help() {
    echo
    echo "$script"
    echo
    echo 'Description: Template nginx proxy conf with env vars.'
    echo "Syntax: $script [-t|-o|help]"
    echo "Example: SERVER_NAME=odoo.example.com PROXY_HOST=http://odoo05 $script -t /usr/share/nginx01/odoo.conf.template -o /usr/share/nginx01/proxies"
    echo 'options:'
    echo '  -t    Path to the proxy conf template.'
    echo '  -o    Output folder of the proxy conf.'
    echo "  help  Show $script manual."
    echo
}

if [[ "$1" == 'help' ]]; then
    help
    exit
fi

while getopts ":t: :o:" opt; do
  case $opt in
    t) template="$OPTARG"
    ;;
    o) output_dir="$OPTARG"
    ;;
    \?) echo "Invalid option -$OPTARG" >&2
    help
    exit 1;;
  esac
done

[[ -z "$template" ]] && { echo 'Parameter -t|template is empty.' ; exit 1; }
[[ -z "$output_dir" ]] && { echo 'Parameter -o|output dir is empty.' ; exit 1; }

output_path="${output_dir}/${SERVER_NAME}.conf"
defined_envs=$(printf '${%s} ' $(env | cut -d= -f1))

echo "Templating nginx proxy conf with these env vars: $defined_envs"
envsubst "$defined_envs" < "$template" > "$output_path"
echo "Nginx proxy conf created: $output_path"
