#!/bin/bash

# Set ssh endpoints for all gears where the application framework is running.
CART_NAME=haproxy
CART_VERSION=1.4

# Exit on any errors
set -e

function log_error() {
    echo "$0: $@" | logger -p local0.err -t openshift_origin_haproxy_set_gear_ep
    return ${1:-1}
}


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_gear_ep
    exit 1
}


function get_registered_endpoints() {
    [ -f "$HAPROXY_GEAR_REGISTRY" ]  &&  cat "$HAPROXY_GEAR_REGISTRY"
}


function register_gear_endpoint() {
    [ $# -lt 3 ]  &&  return 1

    #  Add gear endpoint to registry if it doesn't already exist.
    if ! grep "$1" "$HAPROXY_GEAR_REGISTRY" > /dev/null 2>&1; then
        echo "$3" >> "$HAPROXY_GEAR_REGISTRY"
        if [ -f "$FRAMEWORK_INFO_DIR/bin/sync_gears.sh" ]; then
            run_as_user "$FRAMEWORK_INFO_DIR/bin/sync_gears.sh $2"
        fi
    else
        unregister_gear_endpoint "$1"
        echo "$3" >> "$HAPROXY_GEAR_REGISTRY"
    fi

    return 0
}


function unregister_gear_endpoint() {
    [ $# -lt 1 ]  &&  return 1

    #  Check if the gear endpoint registry entry exists.
    if grep "$1" "$HAPROXY_GEAR_REGISTRY" > /dev/null 2>&1; then
        sed -i "/$1.*/d" "$HAPROXY_GEAR_REGISTRY"
    fi
}


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


[ $# -gt 3 ] || print_help

source /etc/openshift/node.conf
source ${CARTRIDGE_BASE_PATH}/abstract/info/lib/util

setup_configure "$1" $2 $3

import_env_vars

# Defines.
HAPROXY_CONF_DIR=$APP_HOME/$CART_NAME-$CART_VERSION/conf
HAPROXY_GEAR_REGISTRY=$HAPROXY_CONF_DIR/gear-registry.db

framework_carts=($(get_installed_framework_carts))
primary_framework_cart=${framework_carts[0]}
FRAMEWORK_INFO_DIR=${CARTRIDGE_BASE_PATH}/${primary_framework_cart}/info

# Array containing current endpoints.
declare -A curr_endpoints

#  Remove the first 3 args and process all the remaining args of the form
#  key=value. The values contain 'scp-like' endpoints + dns name for each gear.
kvargs=$(echo "${@:4}" | tr -d "\n" )
for arg in $kvargs; do
    zinfo=$(echo "$arg" | cut -f 2 -d '=' | tr -d "'")
    zarr=(${zinfo//;/ })
    ep=${zarr[0]}

    # Ensure endpoint is valid.
    [ -z "$ep" ]  &&  continue

    # And of the form: $app-uuid@$ipv4-address(.*)
    if [[ ! $ep =~ ^[a-zA-Z0-9]{1,32}@[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3} ]]; then
       echo "${@:1:3} - Invalid endpoint '$ep' passed in input - $zinfo" 1>&2
       exit 22
    fi

    zarr2=(${zinfo//@/ })
    gname=${zarr2[0]}
    curr_endpoints[$gname]="$zinfo"
    if [ "$gname" != "$OPENSHIFT_GEAR_UUID" ]; then
        register_gear_endpoint "$gname" "$ep" "$zinfo"  ||  :
    fi
done

# Get a list of all the registered endpoints and remove the endpoints which
# are not in the current set.
for zinfo in $(get_registered_endpoints); do
    zarr=(${zinfo//@/ })
    gname=${zarr[0]}
    if [ -z "${curr_endpoints[$gname]}" ]; then
        unregister_gear_endpoint "$gname" ||  :
    fi
done

uuid=$3
setup_user_vars
run_as_user "app_ctl.sh cond-reload"
