#!/bin/bash

#set esmond env variables
export ESMOND_ROOT=/usr/lib/esmond
export ESMOND_CONF=/etc/esmond/esmond.conf
export DJANGO_SETTINGS_MODULE=esmond.settings

#initialize python
cd $ESMOND_ROOT
source /opt/rh/python27/enable
/opt/rh/python27/root/usr/bin/virtualenv --prompt="(esmond)" .
. bin/activate

#build esmond tables
python esmond/manage.py syncdb --noinput &> /dev/null

#create api key
KEY=`python esmond/manage.py add_api_key_user perfsonar 2> /dev/null | grep "Key:" | cut -f2 -d " "`

#put api key in regular_testing
if [ -n "$KEY" ]; then
    grep -q 'esmond/latency' /etc/perfsonar/regulartesting.conf
    if [ $? != 0 ]; then
        mv /etc/perfsonar/regulartesting.conf /etc/perfsonar/regulartesting.conf.install.back
        cp -f /etc/perfsonar/toolkit/default_service_configs/regular_testing.conf /etc/perfsonar/regulartesting.conf 
    fi

    grep -q ESMOND_API_KEY /etc/perfsonar/regulartesting.conf
    if [ $? == 0 ]; then
        sed -i "s/ESMOND_API_KEY/$KEY/g" /etc/perfsonar/regulartesting.conf
    fi
fi

if [ -f /opt/perfsonar_ps/PingER/etc/pinger-landmarks.xml -o /opt/perfsonar_ps/perfsonarbuoy_ma/etc/owmesh.conf  ]; then
    /usr/lib/perfsonar/scripts/upgrade/upgrade_regular_tests
fi

#set powstream test ports if no default parameters
TESTPORTS=`grep -m 1 '^testports' /etc/owamp-server/owamp-server.conf | cut -f2 -d " "`
if [ -n "$TESTPORTS" ]; then
    RECVPORTS_SET=`grep receive_port_range /etc/perfsonar/regulartesting.conf`
    if [ -z "$RECVPORTS_SET" ]; then
       echo "" >> /etc/perfsonar/regulartesting.conf
       echo "#Default testports set by automated toolkit script" >> /etc/perfsonar/regulartesting.conf
       echo "<default_parameters>" >> /etc/perfsonar/regulartesting.conf
       echo "   type  powstream" >> /etc/perfsonar/regulartesting.conf
       echo "   receive_port_range $TESTPORTS" >> /etc/perfsonar/regulartesting.conf
       echo "</default_parameters>" >> /etc/perfsonar/regulartesting.conf
    fi
fi 
