#!/bin/bash

function usage
{
    echo "usage: startup-marmaserver {dhcp|static} [static ip address]"
}

APPNAME=marmaserver
APPDIR=/opt/midas/bin
MODE=${1}
IPADDRESS=${2}

# figure out which network device to use
if [ -n "`ip addr | grep inet | grep bond0`" ]; then
    # DL3/XL8 use bonded eth0/1
    NETWORKDEVICE=bond0
else
    # DL1/2 use two separate ports
    NETWORKDEVICE=eth1
fi

# arg checking
if [ "${1}" != "dhcp" ] && [ "${1}" != "static" ]; then
    echo "invalid mode arg"
    usage
    exit 1
fi

if [ "${MODE}" == "static" ] && [ -z "${IPADDRESS}" ]; then
    echo "ip address arg is required for static mode"
    usage
    exit 1
fi

# purge log files pre-Birchen logging (newer logs have suffix .txt)
LOGDIR=/opt/midas/var/logs/marmaserver
rm -rf /opt/midas/var/logs/marmaserver/*.log

# function for DL2/DL1 where eth0/1 are bridged by default
function demolishBridge
{
    # simple DL1/2 test
    if [ ${NETWORKDEVICE} == "eth1" ]; then
        if [ `brctl show | grep ${NETWORKDEVICE}` ]; then
            echo "removing ethernet bridge.."
            brctl delif br0 ${NETWORKDEVICE}
        fi
    fi
}

# run the app
echo "shutting down previous invocations.."
pkill ${APPNAME}
demolishBridge
echo "launching marmaserver, mode=${MODE} ip address=${IPADDRESS}"
cd ${APPDIR}
${APPDIR}/${APPNAME} --mode=${MODE} --ip-address=${IPADDRESS}

