################################################################################
#
# Copyright (c) 2015, EURECOM (www.eurecom.fr)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
#    list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and documentation are those
# of the authors and should not be interpreted as representing official policies,
# either expressed or implied, of the FreeBSD Project.
#
################################################################################
# file build_helper
# brief
# authors Laurent Thomas, Lionel GAUTHIER
#
#######################################
SUDO='sudo -E'

###############################
## echo and  family
###############################
black='\E[30m'
red='\E[31m'
green='\E[32m'
yellow='\E[33m'
blue='\E[1;34m'
magenta='\E[35m'
cyan='\E[36m'
white='\E[37m'
reset_color='\E[00m'
COLORIZE=1

cecho()  {  
    # Color-echo
    # arg1 = message
    # arg2 = color
    local default_msg="No Message."
    message=${1:-$default_msg}
    color=${2:-$green}
    [ "$COLORIZE" = "1" ] && message="$color$message$reset_color"
    echo -e "$message"
    return
}

echo_error()   { cecho "$*" $red          ;}
echo_fatal()   { cecho "$*" $red; exit -1 ;}
echo_warning() { cecho "$*" $yellow       ;}
echo_success() { cecho "$*" $green        ;}
echo_info()    { cecho "$*" $blue         ;}



###########################
# Cleaners
###########################

clean_kernel() {
    $SUDO modprobe ip_tables
    $SUDO modprobe x_tables
    $SUDO iptables -P INPUT ACCEPT
    $SUDO iptables -F INPUT
    $SUDO iptables -P OUTPUT ACCEPT
    $SUDO iptables -F OUTPUT
    $SUDO iptables -P FORWARD ACCEPT
    $SUDO iptables -F FORWARD
    $SUDO iptables -t nat -F
    $SUDO iptables -t mangle -F
    $SUDO iptables -t filter -F
    $SUDO iptables -t raw -F
    echo_info "Flushed iptables"
    $SUDO rmmod nasmesh > /dev/null 2>&1
    $SUDO rmmod oai_nw_drv  > /dev/null 2>&1
    $SUDO rmmod openair_rf > /dev/null 2>&1
    $SUDO rmmod ue_ip > /dev/null 2>&1
    echo_info "removed drivers from kernel"
}

clean_all_files() {
 set_openair_env
 dir=$OPENAIR_DIR/cmake_targets
 rm -rf $dir/log $OPENAIR_DIR/targets/bin/* 
 rm -rf $dir/lte_build_oai $dir/lte-simulators/build
 rm -rf $dir/oaisim_build_oai/build $dir/oaisim_build_oai/CMakeLists.txt
 rm -rf $dir/autotests/bin $dir/autotests/log $dir/autotests/*/build 
}

###################################
# Compilers
###################################

compilations() {
  cd $OPENAIR_DIR/cmake_targets/$1/build
  {
    rm -f $3
    make -j`nproc` $2 VERBOSE=$VERBOSE_COMPILE
  } > $dlog/$2.$REL.txt 2>&1
  echo_info "Log file for compilation has been written to: $dlog/$2.$REL.txt"
  if [ -s $3 ] ; then
     cp $3 $4
     echo_success "$2 compiled"
  else
     echo_error "$2 compilation failed"
  fi
}

############################################
# External packages installers
############################################

install_nettle_from_source() {
    cd /tmp
    echo "Downloading nettle archive"
    rm -rf /tmp/nettle-2.5.tar.gz* /tmp/nettle-2.5
    wget ftp://ftp.lysator.liu.se/pub/security/lsh/nettle-2.5.tar.gz 
    tar -xzf nettle-2.5.tar.gz
    cd nettle-2.5/
    ./configure --disable-openssl --enable-shared --prefix=/usr 
    echo "Compiling nettle"
    make -j`nproc`
    make check 
    $SUDO make install 
    rm -rf /tmp/nettle-2.5.tar.gz /tmp/nettle-2.5
}

install_gnutls_from_source(){
    cd /tmp 
    echo "Downloading gnutls archive"
    rm -rf /tmp/gnutls-3.1.23.tar.xz* /tmp/gnutls-3.1.23
    wget ftp://ftp.gnutls.org/gcrypt/gnutls/v3.1/gnutls-3.1.23.tar.xz 
    tar -xzf gnutls-3.1.23.tar.xz
    cd gnutls-3.1.23/
    ./configure --prefix=/usr
    echo "Compiling gnutls"
    make -j`nproc`
    $SUDO make install 
    rm -rf /tmp/gnutls-3.1.23.tar.xz /tmp/gnutls-3.1.23
}



check_install_usrp_uhd_driver(){
        v=$(lsb_release -cs)
        $SUDO apt-add-repository "deb http://files.ettus.com/binaries/uhd/repo/uhd/ubuntu/$v $v main"
        $SUDO apt-get update
        $SUDO apt-get -y install  python python-tk libboost-all-dev libusb-1.0-0-dev
        $SUDO apt-get -y install -t `lsb_release -cs` uhd --force-yes
}
check_install_bladerf_driver(){
	$SUDO add-apt-repository -y ppa:bladerf/bladerf
	$SUDO apt-get update
	$SUDO apt-get install -y bladerf libbladerf-dev
	$SUDO apt-get install bladerf-firmware-fx3
	$SUDO apt-get install bladerf-fpga-hostedx40	
	bladeRF-cli --flash-firmware /usr/share/Nuand/bladeRF/bladeRF_fw.img	
}

check_install_additional_tools (){
    $SUDO apt-get update
    $SUDO apt-get install -y \
	check \
	dialog \
	dkms \
	gawk \
	libboost-all-dev \
	libpthread-stubs0-dev \
	openvpn \
	phpmyadmin \
	pkg-config \
	python-dev  \
	python-pexpect \
	sshfs \
	swig  \
	tshark \
	uml-utilities \
	unzip  \
	valgrind  \
	vlan	  \
	ctags
}

check_install_oai_software() {
    
    $SUDO apt-get update
    $SUDO apt-get install -y \
    autoconf  \
	automake  \
	bison  \
	build-essential \
	cmake \
	cmake-curses-gui  \
	doxygen \
	doxygen-gui\
	texlive-latex-base\
	ethtool \
	flex  \
    gccxml \
    gdb  \
    git \
	graphviz \
	gtkwave \
	guile-2.0-dev  \
	iperf \
	iproute \
	iptables \
	iptables-dev \
	libatlas-base-dev \
	libatlas-dev \
	libblas3gf \
	libblas-dev \
	libconfig8-dev \
	libforms-bin \
	libforms-dev \
	libgcrypt11-dev \
	libgmp-dev \
	libgtk-3-dev \
	libidn2-0-dev  \
    libidn11-dev \
	libmysqlclient-dev  \
	liboctave-dev \
	libpgm-5.1 \
	libpgm-dev \
	libsctp1  \
	libsctp-dev  \
	libssl-dev  \
	libtasn1-3-dev  \
	libtool  \
	libusb-1.0-0-dev \
	libxml2 \
	libxml2-dev  \
	linux-headers-`uname -r` \
	mscgen  \
	octave \
	octave-signal \
	openssh-client \
	openssh-server \
	openssl \
	python  \
	subversion \
        xmlstarlet
    $SUDO update-alternatives --set liblapack.so /usr/lib/atlas-base/atlas/liblapack.so
    if [ `lsb_release -rs` = '12.04' ] ; then
        install_nettle_from_source
        install_gnutls_from_source
    else
        $SUDO apt-get install -y libgnutls-dev nettle-dev nettle-bin 
    fi
    install_asn1c_from_source
}

install_asn1c_from_source(){
    mkdir -p /tmp/asn1c-r1516
    cd /tmp/asn1c-r1516
    rm -rf /tmp/asn1c-r1516/*
    svn co https://github.com/vlm/asn1c/trunk  /tmp/asn1c-r1516 -r 1516 > /tmp/log_compile_asn1c
    patch -p0 < $OPENAIR_DIR/openair3/S1AP/MESSAGES/ASN1/asn1cpatch.p0 >> /tmp/log_compile_asn1c
    patch -p0 < $OPENAIR_DIR/openair3/S1AP/MESSAGES/ASN1/asn1cpatch_2.p0 >> /tmp/log_compile_asn1c
    patch -p0 < $OPENAIR_DIR/openair2/RRC/LITE/MESSAGES/asn1c/asn1cpatch.p0 >> /tmp/log_compile_asn1c
    patch -p0 < $OPENAIR_DIR/openair3/S1AP/MESSAGES/ASN1/asn1cpatch_3.p0 >> /tmp/log_compile_asn1c
    ./configure
    make > /tmp/log_compile_asn1c 2>&1
    $SUDO make install
}

#################################################
# 2. compile 
################################################

install_nas_tools() {
  cd $1
  if [ ! -f .ue.nvram ]; then
    echo_success "generate .ue_emm.nvram .ue.nvram"
    ./nvram --gen
  else
    [ ./nvram -nt .ue.nvram  -o ./nvram -nt .ue_emm.nvram ] && ./nvram --gen
  fi

  if [ ! -f .usim.nvram ]; then
    echo_success "generate .usim.nvram"
    ./usim --gen
  else
    [ ./usim -nt .usim.nvram ] && ./usim --gen
  fi

}
#################################################
# 3. Network interfaces utilities 
################################################

cidr2mask(){
  local i mask=""
  local full_octets=$(($1/8))
  local partial_octet=$(($1%8))

  for ((i=0;i<4;i+=1)); do
    if [ $i -lt $full_octets ]; then
      mask+=255
    elif [ $i -eq $full_octets ]; then
      mask+=$((256 - 2**(8-$partial_octet)))
    else
      mask+=0
    fi
    test $i -lt 3 && mask+=.
  done

  echo $mask
}

# example: netcalc 192.168.12.100 255.255.255.0
netcalc(){
  local IFS='.' ip i
  local -a oct msk
    
  read -ra oct <<<"$1"
  read -ra msk <<<"$2"

  for i in ${!oct[@]}; do
    ip+=( "$(( oct[i] & msk[i] ))" )
  done
    
  echo "${ip[*]}"
}

# example: 
bcastcalc(){
  local IFS='.' ip i
  local -a oct msk
    
  read -ra oct <<<"$1"
  read -ra msk <<<"$2"

  for i in ${!oct[@]}; do
    ip+=( "$(( oct[i] + ( 255 - ( oct[i] | msk[i] ) ) ))" )
  done
  echo "${ip[*]}"
}


is_real_interface(){
  my_bool=1
  for var in "$@"
  do
    if [ "a$var" == "a" ]; then
      return 0
    fi
    if [ "a$var" == "anone" ]; then
      return 0
    fi
    IF=`cat /etc/udev/rules.d/70-persistent-net.rules | grep $var | sed 's/^.*NAME=//' | tr -d '"'`
    if [ "$IF" == "$var" ]; then
      if [ "a${var:0:3}" != "aeth" ]; then
        if [ "a${var:0:4}" != "awlan" ]; then
          if [ "a${var:0:4}" != "awifi" ]; then
            my_bool=0;
          fi
        fi
      fi
    fi
  done
  return $my_bool
}

is_virtual_interface(){
  my_bool=1
  for var in "$@"
  do
    if [ "a$var" == "a" ]; then
      return 0
    fi
    if [ "a$var" == "anone" ]; then
      return 0
    fi
    num=`expr index "$var" :`
    
    if [ $num -eq 0 ]; then
      my_bool=0;
    fi
  done
  return $my_bool
}

# arg1 = interface name
# arg2 = ipv4 addr cidr
set_interface_up(){
  interface=$1
  address=${2%/*} #part before '/'
  cidr_netmask=${2#*/} # part after '/'

  if [ "a${interface:0:4}" == "anone" ]; then
    return;
  fi
  echo "ifconfig  $interface up"
  $SUDO ifconfig  $interface up
  sync
  netmask=`cidr2mask $cidr_netmask`
  broadcast=`bcastcalc $address $netmask`
  echo "ip -4 addr add  $address/$cidr_netmask broadcast $broadcast dev $interface"
  $SUDO ip -4 addr add  $address/$cidr_netmask broadcast $broadcast dev $interface
  sync
}

# arg1 = interface name
# arg2 = ipv4 addr cidr
set_virtual_interface_up(){
  interface=$1
  address=${2%/*} #part before '/'
  cidr_netmask=${2#*/} # part after '/'

  if [ "a${interface:0:4}" == "anone" ]; then
    return;
  fi
  $SUDO ifconfig  $interface down > /dev/null 2>&1
  sync
  echo "ifconfig  $interface $address up"
  $SUDO ifconfig  $interface $address up
  sync
}

#arg1 is interface name
#arg2 is IP address (CIDR)
set_network_interface(){
  local interface_name=$1
  local ip_cidr=$2
  
  is_virtual_interface $interface_name
  if [ $? -eq 1 ]; then
    echo "$interface_name is virtual interface"
    set_virtual_interface_up $interface_name $ip_cidr
  else 
    is_real_interface $interface_name
    if [ $? -eq 1 ]; then
      echo "$interface_name is real interface"
      set_interface_up $interface_name $ip_cidr
    else
      echo_warning "$interface_name not handled, not configuring it"
      return
    fi
  fi
}

# arg1 is a 'libconfig-like' config file
set_epc_network_interfaces(){
  value="`cat $1 | cut -d "#" -f1 | grep 'ADDRESS\|INTERFACE' | tr -d " " | grep "="`"
  eval $value
  
  # check all var names are correct
  list_var_name="\
        ENB_INTERFACE_NAME_FOR_S1_MME         ENB_IPV4_ADDRESS_FOR_S1_MME \
        ENB_INTERFACE_NAME_FOR_S1U            ENB_IPV4_ADDRESS_FOR_S1U "
  for var_name in $list_var_name
  do
    if [ -n "$${var_name}" ]; then
      echo_success "Found ${var_name} = ${!var_name}"
    else
      echo_fatal "${var_name} does does not exist in your config file $1"
    fi
  done

  # configure interfaces
  set_network_interface  $ENB_INTERFACE_NAME_FOR_S1_MME         $ENB_IPV4_ADDRESS_FOR_S1_MME 
  set_network_interface  $ENB_INTERFACE_NAME_FOR_S1U            $ENB_IPV4_ADDRESS_FOR_S1U 
}



################################
# set_openair_env
###############################
set_openair_env(){
    fullpath=`readlink -f $BASH_SOURCE`
    [ -f "/.$fullpath" ] || fullpath=`readlink -f $PWD/$fullpath`
    openair_path=${fullpath%/cmake_targets/*}
    openair_path=${openair_path%/targets/*}
    openair_path=${openair_path%/openair[123]/*}    
    export OPENAIR_DIR=$openair_path
    export OPENAIR1_DIR=$openair_path/openair1
    export OPENAIR2_DIR=$openair_path/openair2
    export OPENAIR3_DIR=$openair_path/openair3
    export OPENAIR_TARGETS=$openair_path/targets
}

