#!/bin/bash
set -e
NUM_JOBS=${NUM_JOBS:--j8}
RUN=${RUN:-"ON"}
AS_ROOT=${AS_ROOT:-"OFF"}

function make_service() {
  mkdir -p build
  pushd build
  cmake .. "$@"
  make $NUM_JOBS
  popd
}

# check that at least there is a cmake script here
if [ ! -f CMakeLists.txt ]; then
   echo "There must be at least a CMakeLists.txt in service folder"
   exit 1
fi
make_service "$@"

if [[ "$RUN" = "ON" ]]; then
  #sudo mknod /dev/net/tap c 10 200
  BINARY=build/"`cat build/binary.txt`"
  # run with GDB
  if [[ "$DBG" = "ON" ]]; then
    BINARY="gdb $BINARY"
  fi
  # run as root with sudo
  if [[ "$AS_ROOT" = "ON" ]]; then
    BINARY="sudo $BINARY"
  fi
  $BINARY
fi
