#! /bin/bash -ex

compile_flag=0
offload_flag=0
assign_ip_flag=0
location=$(pwd)
nic_function_loc="$location/../repository/nic_functions"
# cfiles=ls $nic_function_loc | egrep "*.c"
while getopts 'coi' flag; do
  case "${flag}" in
    c) compile_flag=1 ;;
    o) offload_flag=1 ;;
    i) assign_ip_flag=1 ;;
  esac
done

if [[ $compile_flag -eq 1 ]]
then
    # compile the nfp code
    # sudo /opt/netronome/p4/bin/nfp4build -o ./p4src/orchestrator.nffw -p ./p4src/out -4 ./p4src/orchestrator.p4 -l lithium --nfp4c_p4_version 16 --nfirc_mac_ingress_timestamp --nfp4c_p4_compiler p4c-nfp 
    #  for function running in host
    sudo /opt/netronome/p4/bin/nfp4build -o ./p4src/orchestrator_speedo.nffw -p ./p4src/out -4 ./p4src/orchestrator_speedo.p4  -c ./p4src/static_dispatch_function.c ./p4src/nic_function_test.c -l lithium --nfp4c_p4_version 16 --nfirc_mac_ingress_timestamp --nfp4c_p4_compiler p4c-nfp 
    # for function running on nic
    # sudo /opt/netronome/p4/bin/nfp4build -o ./p4src/orchestrator_static.nffw -p ./p4src/out -4 ./p4src/orchestrator_static.p4 -c ./p4src/static_dispatch_function.c ./p4src/nic_function_test.c -l lithium --nfp4c_p4_version 16 --nfirc_mac_ingress_timestamp --nfp4c_p4_compiler p4c-nfp 

    # sudo /opt/netronome/p4/bin/nfp4build -o ./p4src/orchestrator_dynamic.nffw -p ./p4src/out -4 ./p4src/orchestrator_dynamic.p4 -c ./p4src/static_dispatch_function.c ./p4src/nic_function_test.c -l lithium --nfp4c_p4_version 16 --nfirc_mac_ingress_timestamp --nfp4c_p4_compiler p4c-nfp 
    #cd $nic_function_loc
    #files=$(./generate_names.sh)
    #cd $location
    #echo "files : $files"
    #sudo /opt/netronome/p4/bin/nfp4build -o ./p4src/orchestrator.nffw -p ./p4src/out -4 ./p4src/orchestrator.p4 -c $files  -l lithium --nfp4c_p4_version 16 --nfirc_mac_ingress_timestamp --nfp4c_p4_compiler p4c-nfp 

fi

if [[ $offload_flag -eq 1 ]]
then
  # move to p4 bin
  cd /opt/netronome/p4/bin/

  # offload
  sudo ./rtecli design-load -f $location/p4src/orchestrator_speedo.nffw -c $location/p4src/echo2.p4cfg -p $location/p4src/out/pif_design.json
  # sudo ./rtecli design-load -f $location/p4src/orchestrator_static.nffw -c $location/p4src/echo.p4cfg -p $location/p4src/out/pif_design.json
  
  # sudo ./rtecli design-load -f $location/p4src/orchestrator_dynamic.nffw -c $location/p4src/echo.p4cfg -p $location/p4src/out/pif_design.json
  # returning back to base
  cd $location
fi

if [[ $assign_ip_flag -eq 1 ]]
then
    #killing all running containers
    docker stop $(docker ps -a -q) || true
    #assigning IPs to network interfaces
    sudo ./assign_ip.sh
fi