#!/usr/bin/env bash

. /usr/share/dosis2/bin/shell-support-functions

#===============================
# Create a temporary cookies file
# to save credentials
#===============================
COOKIES="tmp.cookies"
FILE_EXT="tar"

function cleanup {
    echo "Cleaning up cookies..."
    rm -f ${COOKIES}
}
trap cleanup EXIT

PIRANHA=`nslookup piranha.swamp.alex`
if [[ $? != 0 ]]; then
	PIRANHA="10.120.1.102"
else
	PIRANHA="piranha"
fi

if [[ -z "${FILE}" ]]; then
	FILE=`hostname | cut -d '.' -f 1 | sed -e "s/-/_/g" | tr '[[:lower:]]' '[[:upper:]]'`
	FILE="${FILE}.${FILE_EXT}"
fi

echo "Connecting to piranha: ${PIRANHA}"
echo "Please Enter the password"
read -s -p "Password: " PASSWORD

wget --delete-after --keep-session-cookies --save-cookies ${COOKIES} --post-data "username=support&password=${PASSWORD}" "${PIRANHA}:5000/login_webhead"
if [[ $? != 0 ]]; then
	echo "Wrong username and/or password"
	exit 1
fi

wget --load-cookies ${COOKIES} "${PIRANHA}:5000/view_keytars/eqp/?filename=${FILE}" -O /etc/openvpn/${FILE}
if [[ $? != 0 ]]; then
    # if we fail with this hostname, we wanna try grabbing a key with the name L60_D<serial>
    # since dafe serials are unique and piranha may have made the key with the name L60 instead
    # of the previous name, we will try to grab that key from piranha and use it
    FILE=${FILE/[A-Z]60/L60}
    wget --load-cookies ${COOKIES} "${PIRANHA}:5000/view_keytars/eqp/?filename=${FILE}" -O /etc/openvpn/${FILE}
    if [[ $? != 0 ]]; then
        echo "File ${FILE} not found on piranha server"
        echo "  this could mean it has not been provisioned"
        echo "  yet or piranha server is down"
        exit 1
    fi
fi

tar xvf /etc/openvpn/${FILE} -C /etc/openvpn/.

if [ "`getos`" = "CentOS" ]; then
    service openvpn restart
else
    systemctl restart openvpn@vpn_alex
    systemctl restart openvpn@vpn_awse2b
    systemctl restart openvpn@vpn_awse2c
fi

watch -n2 'echo "wait for some tun interfaces to show up then hit CTRL+C";ifconfig tun0 2>/dev/null||echo "tun0 not available";ifconfig tun1 2>/dev/null||echo "tun1 not available"'

exit 0
