#!/bin/bash

CONFFILE="/etc/ipfixprobe/$1.conf"

if [ -e "$CONFFILE" ]; then
   source "$CONFFILE"
   input=""
   dpdkinput=""
   if [ "$USE_DPDK" = "1" ]; then
      # check
      if [ -z "$DPDK_QUEUES_COUNT" ]; then
         echo "Missing DPDK_QUEUES_COUNT in configuration of DPDK mode."
         exit 1
      fi

      # set up DPDK interface(s)
      if [ "$DPDK_RING" = "1" ]; then
         # checks
         if [ -z "$DPDK_RING_PATTERN" ]; then
            echo "Missing DPDK_RING_PATTERN in configuration of DPDK_RING mode."
            exit 1
         fi
         if [ -z "$DPDK_RING_STARTIDX" ]; then
            echo "Missing DPDK_RING_STARTIDX in configuration of DPDK_RING mode, using 0."
            DPDK_RING_STARTIDX=0
         fi
         # mring interfaces
         dpdkinput=("-i" "dpdk-ring;r=$(printf "$DPDK_RING_PATTERN" "$DPDK_RING_STARTIDX");e=--lcores $DPDK_LCORES $DPDK_EXTRA_EAL")
         for ((ifc=($DPDK_RING_STARTIDX+1); ifc<($DPDK_RING_STARTIDX + $DPDK_QUEUES_COUNT);ifc++)); do
            dpdkinput+=("-i" "dpdk-ring;r=$(printf "$DPDK_RING_PATTERN" "$ifc")")
         done
      else
         # DPDK port interface
         if [ -n "$DPDK_PORTOPTS" -a "${DPDK_PORTOPTS:0:1}" != ";" ]; then
            DPDK_PORTOPTS=";$DPDK_PORTOPTS"
         fi
         dpdkinput=("-i" "dpdk;p=${DPDK_PORT}${DPDK_PORTOPTS};q=$DPDK_QUEUES_COUNT;e=--lcores $DPDK_LCORES $DPDK_EXTRA_EAL -a $DPDK_DEVICE")
         for ((ifc=1; ifc<$DPDK_QUEUES_COUNT;ifc++)); do
            dpdkinput+=("-i" "dpdk")
         done
      fi
   fi
   if `declare -p INPUT > /dev/null 2>/dev/null`; then
      # list of input plugins
      for ifc in "${!INPUT[@]}"; do
         input="$input -i ${INPUT[ifc]}"
      done
   fi
   CACHE_SIZE_PARAM=""
   if [ ! -z ${CACHE_SIZE+x} ]; then
      CACHE_SIZE_PARAM="size=${CACHE_SIZE}"
   fi
   CACHE_ACTIVET_PARAM=""
   if [ ! -z ${ACTIVE_TIMEOUT+x} ]; then
      CACHE_ACTIVET_PARAM=";active=${ACTIVE_TIMEOUT}"
   fi
   CACHE_INACTIVET_PARAM=""
   if [ ! -z ${INACTIVE_TIMEOUT+x} ]; then
      CACHE_INACTIVET_PARAM=";inactive=${INACTIVE_TIMEOUT}"
   fi
   storage="-s cache;${CACHE_SIZE_PARAM}${CACHE_ACTIVET_PARAM}${CACHE_INACTIVET_PARAM}"
   process=""
   if `declare -p PROCESS > /dev/null 2>/dev/null`; then
      # list of input plugins
      for ifc in "${!PROCESS[@]}"; do
         process="$process -p ${PROCESS[ifc]}"
      done
   fi
   UDP_PARAM=""
   if [[ $UDP == "yes" ]]; then
        UDP_PARAM="udp";
   fi
   output="-o ipfix;host=${HOST:-127.0.0.1};port=${PORT:-4739};id=${LINK:-0};dir=${DIR:-0};${UDP_PARAM};template=${TEMPLATE_REFRESH_RATE:-300}"

   exec /usr/bin/ipfixprobe "${dpdkinput[@]}" $input $storage $process $output
else
   echo "Configuration file '$CONFFILE' does not exist, exitting." >&2
   exit 1
fi
