#!/bin/bash

# Set ssh endpoints for all gears where the application framework is running.
# 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
        # Lock gear-registry.db for the duration of the script
        flock 201
        echo "$3" >> "$HAPROXY_GEAR_REGISTRY"
        flock -u 201
        $OPENSHIFT_HAPROXY_DIR/bin/deploy $2
    else
        unregister_gear_endpoint "$1"
        flock 201
        echo "$3" >> "$HAPROXY_GEAR_REGISTRY"
        flock -u 201
    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
        flock 201
        sed -i "/$1.*/d" "$HAPROXY_GEAR_REGISTRY"
        flock -u 201
    fi
}


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


[ $# -gt 3 ] || print_help

# Defines.
HAPROXY_CONF_DIR=$OPENSHIFT_HAPROXY_DIR/conf
HAPROXY_GEAR_REGISTRY=$HAPROXY_CONF_DIR/gear-registry.db
HAPROXY_CONFIG=$HAPROXY_CONF_DIR/haproxy.cfg

# Establish locking file descriptor
exec 201>${HAPROXY_GEAR_REGISTRY}.lock

# 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

# Disable the local endpoint if one of the remote gears is available and it
# isn't already disabled
if [ $(grep -E "server\s*gear" $HAPROXY_CONFIG | wc -l) -ge 2 ]; then
    if grep "local-gear" $HAPROXY_CONFIG | grep "weight 0" &>/dev/null; then
        echo "Local gear already disabled in config. "
    else
        echo "Disabling local gear in the config. "
        nohup $OPENSHIFT_HAPROXY_DIR/usr/bin/fix_local.sh &
    fi
fi

/usr/bin/gear reload --cart haproxy-$OPENSHIFT_HAPROXY_VERSION
