#!/bin/bash

# Start the application httpd instance

# Exit on any errors
set -e

function print_help {
    echo "Usage: $0 app-name namespace uuid"
    echo "Start a running application"

    echo "$0 $@" | logger -p local0.notice -t openshift_origin_haproxy_set_db_connection_info
    exit 1
}

while getopts 'd' OPTION
do
    case $OPTION in
        d) set -x
        ;;
        ?) print_help
        ;;
    esac
done


[ $# -ge 3 ] || print_help

cartridge_type="haproxy-1.4"
source "/etc/openshift/node.conf"
source ${CARTRIDGE_BASE_PATH}/abstract/info/lib/util

setup_configure "$1" $2 $3

import_env_vars

HAPROXY_DIR=$(get_cartridge_instance_dir "$cartridge_type")

# Remove the first 3 args and process all the remaining args of the form k=v.
# The values are the db environment variable name-value pairs.
shift; shift; shift;
while [ $# -gt 0 ]; do
    arg=$1
    shift
    nvs=$(echo "$arg" | tr "\n" ";" | cut -f 2- -d '=' | sed "s/'\(.*\)'/\\1/")
    echo "$nvs" | tr ";" "\n" |  while read line; do
        [ -z "$line" ]  &&  continue
        #  Got a name-value pair - add to userenv.
        name=$(echo "$line" | cut -f 1 -d '=')
        value=$(echo "$line" | cut -f 2- -d '=')
        [ -n "$name" ]  &&  echo "$value" > $APP_HOME/.env/.uservars/$name
    done
done
