#!/bin/bash

SYSTEM_TYPE="$1"
NEW_HOSTNAME="$2"

function die() {
    echo "!! $1"
    exit 1
}

OS="`/usr/share/dosis2/bin/whichos`"

# normalize the passed in hostname
NEW_HOSTNAME="`echo ${NEW_HOSTNAME/_/-} | tr '[[:upper:]]' '[[:lower:]]'`"

if [ -z "${NEW_HOSTNAME}" ] || [ -z "${SYSTEM_TYPE}" ]; then
    echo "Usage: setup-dosis-network system-type hostname"
    echo "  system-types: L60, C60, U60, SITE_SERVER"
    echo ""
    echo "  Example: setup-dosis-network L60 L60_D205"
fi

if [ "${SYSTEM_TYPE}" = "L60" ] || [ "${SYSTEM_TYPE}" = "C60" ]; then
	echo "Setting hostname: ${NEW_HOSTNAME}"
    /opt/dosis2/bin/configure-network hostname --quiet --set "${NEW_HOSTNAME}"

    echo "Setting eth0 as network card"
    /opt/dosis2/bin/configure-network preset eth0 --preset network

    echo "Setting eth1 as camera card"
    /opt/dosis2/bin/configure-network preset eth1 --preset camera

    #need to set mtu with script until they fix netplan bug
    SET_MTU_SCRIPT="/usr/lib/networkd-dispatcher/routable.d/set-camera-mtu.bash"
    touch ${SET_MTU_SCRIPT}
    chmod a+x ${SET_MTU_SCRIPT}
    echo "#!/bin/bash" >> ${SET_MTU_SCRIPT}
    echo "ip link set eth1 mtu 8228" >> ${SET_MTU_SCRIPT}

    echo "Setting eth2 as printer card"
    /opt/dosis2/bin/configure-network preset eth2 --preset printer

elif [ "${SYSTEM_TYPE}" = "U60" ]; then
	echo "Setting hostname: ${NEW_HOSTNAME}"
    /opt/dosis2/bin/configure-network hostname --quiet --set "${NEW_HOSTNAME}"

    echo "Setting eth0 as network card"
    /opt/dosis2/bin/configure-network preset eth0 --preset network

    echo "Setting eth1 as camera card"
    /opt/dosis2/bin/configure-network preset eth1 --preset camera

    #need to set mtu with script until they fix netplan bug
    SET_MTU_SCRIPT="/usr/lib/networkd-dispatcher/routable.d/set-camera-mtu.bash"
    touch ${SET_MTU_SCRIPT}
    chmod a+x ${SET_MTU_SCRIPT}
    echo "#!/bin/bash" >> ${SET_MTU_SCRIPT}
    echo "ip link set eth1 mtu 8228" >> ${SET_MTU_SCRIPT}

    echo "Setting eth2 as printer card"
    /opt/dosis2/bin/configure-network preset eth2 --preset printer

    echo "Setting eth3 as lor card"
    /opt/dosis2/bin/configure-network preset eth3 --preset lor
elif [ "${SYSTEM_TYPE}" = "SITE_SERVER" ]; then
	echo "Setting hostname: ${NEW_HOSTNAME}"
    /opt/dosis2/bin/configure-network hostname --quiet --set "${NEW_HOSTNAME}"

    echo "Setting eth0 as network card"
    /opt/dosis2/bin/configure-network preset eth0 --preset network

    echo "Disabling eth1 card"
    /opt/dosis2/bin/configure-network preset eth1 --preset disabled

    #need to set mtu with script until they fix netplan bug
    SET_MTU_SCRIPT="/usr/lib/networkd-dispatcher/routable.d/set-camera-mtu.bash"
    rm -f ${SET_MTU_SCRIPT}

    echo "Disabling eth2 card"
    /opt/dosis2/bin/configure-network preset eth2 --preset disabled
else
    die "Unknown System Type: ${SYSTEM_TYPE}"
fi
