#!/bin/bash
#Determine install type
# UPDATE: Don't force creation of localhost MAs
# NEW: Add localhost MAs if don't see the API key referenced anywhere else
# FORCE: Add the localhost MA 
INSTALL_TYPE="UPDATE"
if [ "$1" == "new" ]; then
    INSTALL_TYPE="NEW"
elif [ "$1" == "--force" ]; then
    INSTALL_TYPE="FORCE"
fi

#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
. bin/activate

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

#setup localhost measurement archive
if [ -n "$KEY" ]; then
    ADD_LOCAL_MA=0
    #adding an MA will depend on install type and if already saw referenced key
    if [ "$INSTALL_TYPE" == "FORCE" ]; then
        #If we gave it the --force option, definitely add
        ADD_LOCAL_MA=1
    elif [ "$INSTALL_TYPE" == "NEW" ]; then
        #If we are installing from RPM for first time, add if key not referenced
        if [ ! -f "/etc/perfsonar/psconfig/archives.d/esmond_local.json" ]; then
            ADD_LOCAL_MA=1
        fi
    fi

    #finally, drop-in MA if needed
    if [ -d "/etc/perfsonar/psconfig/archives.d" ] && [ $ADD_LOCAL_MA -eq 1 ]; then
        cat >/etc/perfsonar/psconfig/archives.d/esmond_local.json <<EOF
{
    "archiver" : "esmond",
    "data" : {
        "url" : "https://{% scheduled_by_address %}/esmond/perfsonar/archive/",
        "measurement-agent" : "{% scheduled_by_address %}",
        "_auth-token" : "${KEY}"
    }
}
EOF
        #make sure after all the edits local ma file still has proper permissions
        chown perfsonar:perfsonar /etc/perfsonar/psconfig/archives.d/esmond_local.json
        chmod 644 /etc/perfsonar/psconfig/archives.d/esmond_local.json
    fi
fi

#Create archiver file for easy access
mkdir -p /usr/share/pscheduler
if [ -n "$KEY" ] && [ ! -f "/usr/share/pscheduler/psc-archiver-esmond.json" ]; then
cat >/usr/share/pscheduler/psc-archiver-esmond.json <<EOF
{
    "archiver": "esmond",
    "data": {
        "url": "http://localhost/esmond/perfsonar/archive/",
        "_auth-token": "${KEY}"
    }
}
EOF
fi
