#!/bin/sh

sudo kill -9 `ps -ef | grep oaisim | awk '{print $2}'`
sudo pkill oaisim

# set params
EMULATION_DEV_INTERFACE="eth0"
EMULATION_MULTICAST_GROUP=1
EMULATION_LOG_LEVEL=7 # 3 = error, 5 info, 7 debug, trace= 9 
#OAI_LOCAL_ADDRESS="10.0.1.2"
#OAI_REMOTE_ADDRESS="10.0.1.1"
#EMULATION_DEV_ADDRESS= `hostname -I cut -f1 -d' '`
EMULATION_DEV_ADDRESS=`LC_ALL=C ifconfig $EMULATION_DEV_INTERFACE | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'`

echo "Setting Emulation Interface to $EMULATION_DEV_INTERFACE ($EMULATION_DEV_ADDRESS)"

#funcs
test_install_package() {
  # usage: test_install_package package_name
  if [ $# -eq 1 ]; then
      dpkg -s "$1" > /dev/null 2>&1 && {
          echo "$1 is installed." 
      } || {
          echo "$1 is not installed."
          sudo apt-get install --assume-yes $1 
      }
  fi
}
#PGM provide a reliable mutlicast data transport"
test_install_package libpgm-dev 
test_install_package libpgm-5.1-0
PGM_FOUND=`dpkg-query -W -f='${Status}' libpgm-dev 2>/dev/null | grep -c "ok installed" `
if [ $PGM_FOUND = 1 ]; then 
    PGM=-D$EMULATION_DEV_ADDRESS
else 
    PGM=" "
fi 

echo "Building"
sudo rmmod nasmesh
make nasmesh all
sudo insmod  $OPENAIR2_DIR/NAS/DRIVER/MESH/nasmesh.ko 


#avoid conflict with reserved multicast addresses (224.0.0.11,224.0.0.13, 224.0.0.16)
#sudo route add -net 224.0.0.0 netmask 240.0.0.0 dev eth0
echo "Make sure that eth0 is the interface between the machines, otherwise change"
sudo ip route add 239.0.0.160/28 dev $EMULATION_DEV_INTERFACE

# when running as a suduoers, the following lines are not needed
#sudo ifconfig oai0 $OAI_LOCAL_ADDRES netmask 255.255.255.0 broadcast 10.0.1.255
#$OPENAIR2_DIR/NAS/DRIVER/MESH/RB_TOOL/rb_tool -a -c0 -i0 -z0 -s $OAI_LOCAL_ADDRESS -t $OAI_REMOTE_ADDRESS  -r 1

# running oaisim
if   [ -z $1 ]; then 
echo "$OPENAIR_TARGETS/SIMU/USER/oaisim  -b0 -M1 -p2 -g$EMULATION_MULTICAST_GROUP -l$EMULATION_LOG_LEVEL $PGM  > /dev/null"
sudo -E $OPENAIR_TARGETS/SIMU/USER/oaisim  -b0 -M1 -p2 -g$EMULATION_MULTICAST_GROUP -l$EMULATION_LOG_LEVEL $PGM  > /dev/null
else
    if [ $1 = "all" ]; then 
	echo "$OPENAIR_TARGETS/SIMU/USER/oaisim -b0 -M1 -p2 -g$EMULATION_MULTICAST_GROUP -l$EMULATION_LOG_LEVEL $PGM "
	sudo -E $OPENAIR_TARGETS/SIMU/USER/oaisim  -b0 -M1 -p2 -g$EMULATION_MULTICAST_GROUP -l$EMULATION_LOG_LEVEL $PGM 
    else
	echo "$OPENAIR_TARGETS/SIMU/USER/oaisim -b0 -M1 -p2 -g$EMULATION_MULTICAST_GROUP -l$EMULATION_LOG_LEVEL $PGM  | grep -i $1" 
        sudo -E $OPENAIR_TARGETS/SIMU/USER/oaisim  -b0 -M1 -p2 -g$EMULATION_MULTICAST_GROUP -l$EMULATION_LOG_LEVEL $PGM  | grep -i $1
    fi	
fi
echo "End"
