#!/bin/bash

# This script sets up the virtualbox internal vlan used to communicate with the Emulators
#
# It is run by systemd once the configuration shared folder is mounted and it then sets
# up the ethernet for connman; connman will immediately reconfigure the 2nd adapter
DEVICES_XML=/etc/mersdk/share/devices.xml

DEF_SUBNET="10.220.220"
MAC2=$(cat /sys/class/net/eth?/address | grep -iv 08:00:5A:11:F1:55 | sed 's/://g')

read_dom () {
    local IFS=\>
    read -d \< ENTITY CONTENT
    local RET=$?
    TAG_NAME=${ENTITY%% *}
    ATTRIBUTES=${ENTITY#* }
    return $RET
}

get_engine() {
    FOUND=
    while read_dom; do
	case $TAG_NAME in
	    device )
		ENGINE=
		;;
	    engine )
		ENGINE=1
		eval local $ATTRIBUTES
		NAME=$name
		;;
	    subnet )
		if [[ $ENGINE ]]; then
		    eval $TAG_NAME="$CONTENT"
		fi
		;;
	esac
    done
    if [[ $subnet ]]; then
	echo "Will set IP=$subnet.254 for $NAME"
	return 0
    fi
    return 1
}


mkdir -p /var/lib/connman

if [[ -f $DEVICES_XML ]]; then
    if ! get_engine < $DEVICES_XML ; then
	echo "No <engine><subnet> found in devices.xml - using default ($DEF_SUBNET)"
	subnet=$DEF_SUBNET
    fi
else
    echo "$DEVICES_XML not found - using default ($DEF_SUBNET)"
    subnet=$DEF_SUBNET
fi

echo "Setting up SDK Engine internal LAN to $subnet.254"

con_sailfishsdk="ethernet_08005a11f155_cable"
con_nat="ethernet_${MAC2}_cable"

connmanctl services

connmanctl config $con_sailfishsdk ipv4 manual $subnet.254 255.255.255.0 $subnet.253
connmanctl config $con_sailfishsdk ipv6 off
connmanctl connect $con_sailfishsdk

connmanctl config $con_nat ipv4 dhcp
connmanctl config $con_nat ipv6 off
connmanctl connect $con_nat

