#!/bin/bash

cd $(dirname $0)
cd ../lwdproxy

source conf/LWDPROXY

#locate the executable jar:
jar=$(find ../lib -regex '.*/lwdproxy-[0-9].+?.jar')

if [ ! -r "$jar" ]; then
    echo "lwdproxy executable jar not found!"
    exit 1
fi

if [ "$APIPEER" == "" ]; then
    APIPEER=$(/usr/bin/hbrsrv-guestinfo.sh get guestinfo.lwdproxy.apiclient.thumbprint)

    if [ "$APIPEER" == "" ]; then
        echo "Unable to determine API PEER ID"
        #TODO: APIPEER
        #exit 2
    fi
fi

if [[ -x "/usr/bin/hbrsrv-nic.py" ]]; then
    IP_FOR_FILTER=$(/usr/bin/hbrsrv-nic.py -c printall | awk -F \, '{print $1}')
    if [ "$IP_FOR_FILTER" != "" ]; then
        if [[ $IP_FOR_FILTER == *:* ]]; then
            NEXTHOP="lwd://[$IP_FOR_FILTER]:31031"
        else
            NEXTHOP="lwd://$IP_FOR_FILTER:31031"
        fi
    fi
fi

exec "$JAVA" \
    -DAPIPEER="$APIPEER" \
    -DNEXTHOP="$NEXTHOP" \
    -DCONFIGFILE="$CONFIGFILE" \
    -jar "$jar" \
    "$LWDENDPOINT" "$LWDCSENDPOINT" "$APIENDPOINT"
