#!/bin/sh

# usage: getconfig.sh <localconfig> <globalconfig> <plopcontrolfile>

set -o nounset
set -o errexit

BINDIR=$(dirname $0)

localconfig=$1
globalconfig=$2
plopcontrolfile=$3

plopcontrolport=
configversion="unknown"
if [ "${plopcontrolfile}" != "force-compile" -a -f ${plopcontrolfile} ]; then
    plopcontrolport=$(cat ${plopcontrolfile})
    configversion=$(echo "configversion" | nc 127.0.0.1 ${plopcontrolport} || echo unreachable)
fi

echo "version before reload: $configversion"
getconfigresult=$(${BINDIR}/getconfig.py --localconfig ${localconfig} --dest ${globalconfig})
if [ "${plopcontrolfile}" = "force-compile" -o "$getconfigresult" = "newconfig" ]; then
    ${BINDIR}/compileconfig.py --localconfig ${localconfig} --config ${globalconfig}
    if [ "${plopcontrolport}" != "" ]; then
        reloadresult=$(echo "reload" | nc 127.0.0.1 ${plopcontrolport}  || echo unreachable)
        echo $reloadresult
        if [ "$reloadresult" != "reload completed" ]; then
            exit 1
        fi
        configversion=$(echo "configversion" | nc 127.0.0.1 ${plopcontrolport} || echo unreachable)
        echo "version after reload: $configversion"
    fi
else    
    echo "reload not needed"
fi