#!/usr/bin/env bash
# ==========================================================================
#         _   _      _   ____            __ __  __      _
#        | \ | | ___| |_|  _ \ ___ _ __ / _|  \/  | ___| |_ ___ _ __
#        |  \| |/ _ \ __| |_) / _ \ '__| |_| |\/| |/ _ \ __/ _ \ '__|
#        | |\  |  __/ |_|  __/  __/ |  |  _| |  | |  __/ ||  __/ |
#        |_| \_|\___|\__|_|   \___|_|  |_| |_|  |_|\___|\__\___|_|
#
#                  NetPerfMeter -- Network Performance Meter
#                 Copyright (C) 2009-2026 by Thomas Dreibholz
# ==========================================================================
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact:  dreibh@simula.no
# Homepage: https://www.nntb.no/~dreibh/netperfmeter/

# Bash options:
set -eu


# ###### Usage ##############################################################
usage () {
   echo >&2 "Usage: $0 config_file [-w|--own-file] [-k|--keep-summaries] [-p|--per-flow-plots]"
   exit 1
}


# ###### Main program #######################################################

# ====== Handle arguments ===================================================
GETOPT="$(PATH=/usr/local/bin:${PATH} which getopt)"
options="$(${GETOPT} -o wkph --long own-file,ownfile,keep-summaries,per-flow-plots,help -a -- "$@")"
# shellcheck disable=SC2181
if [[ $? -ne 0 ]]; then
   usage
fi

KEEP_SUMMARIES=0
PER_FLOW_PLOTS=0
PLOT_OWN_FILE="FALSE"
eval set -- "${options}"
while [ $# -gt 0 ] ; do
   case "$1" in
      -w | --own-file | --ownfile)
         PLOT_OWN_FILE="TRUE"
         shift
         ;;
      -k | --keep-summaries)
         KEEP_SUMMARIES=1
         shift
         ;;
      -p | --per-flow-plots)
         PER_FLOW_PLOTS=1
         shift
         ;;
      -h | --help)
         usage
         # shift
         ;;
      --)
         shift
         break
         ;;
  esac
  shift
done
if [ $# -ne 1 ] ; then
   usage
fi
CONFIG_FILE="$1"
if [ ! -e "${CONFIG_FILE}" ] ; then
   echo >&2 "ERROR: Config file ${CONFIG_FILE} not found!"
   exit 1
fi


# ====== Check vector files =================================================
echo -e "\e[34mChecking vector files ...\e[0m"
VECTOR_ACTIVE_NODE=""
VECTOR_PASSIVE_NODE=""
NUM_FLOWS=0
# shellcheck disable=SC1090
. "${CONFIG_FILE}"
if [ "${VECTOR_PASSIVE_NODE}" == "" ] || [ "${VECTOR_ACTIVE_NODE}" == "" ] || [ ${NUM_FLOWS} -lt 1 ] ; then
   echo >&2 "ERROR: Bad vector file configuration!"
   exit 1
fi
if [ ! -e "${VECTOR_ACTIVE_NODE}" ] ; then
   echo >&2 "ERROR: Vector file ${VECTOR_ACTIVE_NODE} of active node not found!"
   exit 1
fi
if [ ! -e "${VECTOR_PASSIVE_NODE}" ] ; then
   echo >&2 "ERROR: Vector file ${VECTOR_ACTIVE_NODE} of passive node not found!"
   exit 1
fi
# shellcheck disable=SC2001
OUTPUT_PREFIX="$(echo "${CONFIG_FILE}" | sed -e "s/.config$//g")"

echo "Configuration:"
echo " * Input of Active Node \"${NAME_ACTIVE_NODE}\": ${VECTOR_ACTIVE_NODE}"
echo " * Input of Passive Node \"${NAME_PASSIVE_NODE}\": ${VECTOR_PASSIVE_NODE}"
echo " * Output Prefix: ${OUTPUT_PREFIX}"


# ====== Create combined data files =========================================
echo -e "\e[34mCombining vector files for plotting input ...\e[0m"
SEARCH_PATHS=". /usr/local/bin /usr/bin"
COMBINESUMMARIES="combinesummaries"
for searchPath in ${SEARCH_PATHS} ; do
   if [ -e "${searchPath}/${COMBINESUMMARIES}" ] ; then
      COMBINESUMMARIES="${searchPath}/combinesummaries"
      break
   fi
done

SUMMARY_NAME="${OUTPUT_PREFIX}-summary.data.bz2"
(
   echo -e "--values=\"\"${NAME_ACTIVE_NODE}\"\t1\""
   echo "--input=${VECTOR_ACTIVE_NODE}"
   echo -e "--values=\"\"${NAME_PASSIVE_NODE}\"\t0\""
   echo "--input=${VECTOR_PASSIVE_NODE}"
) | ${COMBINESUMMARIES} "${SUMMARY_NAME}" $'NodeName\tIsActive' --separator $'\t' --line-numbers --quiet

FLOW_SUMMARY_NAME="${OUTPUT_PREFIX}-flows.data.bz2"
(
   i=0
   while [ $i -lt ${NUM_FLOWS} ] ; do
      flowDescriptionVar="\$FLOW$i""_DESCRIPTION"
      activeVectorVar="\$FLOW$i""_VECTOR_ACTIVE_NODE"
      passiveVectorVar="\$FLOW$i""_VECTOR_PASSIVE_NODE"
      flowDescription=""
      activeVector=""
      passiveVector=""
      eval flowDescription="${flowDescriptionVar}"
      eval activeVector="${activeVectorVar}"
      eval passiveVector="${passiveVectorVar}"

      echo -e "--values=\"\"${flowDescription}\"\t$i\t\"${NAME_ACTIVE_NODE}\"\t1\""
      echo "--input=${activeVector}"
      echo -e "--values=\"\"${flowDescription}\"\t$i\t\"${NAME_PASSIVE_NODE}\"\t0\""
      echo "--input=${passiveVector}"
      i=$((i+1))
   done
) | ${COMBINESUMMARIES} "${FLOW_SUMMARY_NAME}" $'FlowName\tFlowID\tNodeName\tIsActive' --separator $'\t' --line-numbers --quiet


# ====== Plot the results ===================================================
echo -e "\e[34mPlotting the vectors ...\e[0m"

# ------ Locate plotting scripts --------------------------------------------
SEARCH_PATHS=". /usr/share/netperfmeter /usr/local/share/netperfmeter"
PLOT_PROGRAM_DIR=""
PLOT_PROGRAM_SCRIPT="plot-netperfmeter-results.R"
for searchPath in ${SEARCH_PATHS} ; do
   if [ -e "${searchPath}/${PLOT_PROGRAM_SCRIPT}" ] ; then
      PLOT_PROGRAM_DIR=${searchPath}
      break
   fi
done
if [ "${PLOT_PROGRAM_DIR}" = "" ] ; then
   echo >&2 "ERROR: Cannot find ${PLOT_PROGRAM_SCRIPT}!"
   exit 1
elif [ "${PLOT_PROGRAM_DIR}" = "." ] ; then
   echo "Using ${PLOT_PROGRAM_SCRIPT} from ${searchPath}"
fi


# ------ Call the R script for plotting -------------------------------------
R CMD BATCH --slave --vanilla \
   "--args
      programDirectory=\"${PLOT_PROGRAM_DIR}\"
      configFile=\"${CONFIG_FILE}\"
      summaryFile=\"${SUMMARY_NAME}\"
      flowSummaryFile=\"${FLOW_SUMMARY_NAME}\"
      pdfFilePrefix=\"${OUTPUT_PREFIX}\"
      perFlowPlots=${PER_FLOW_PLOTS}
      plotOwnFile=${PLOT_OWN_FILE}" \
   "${PLOT_PROGRAM_DIR}/${PLOT_PROGRAM_SCRIPT}" /dev/stdout


# ====== Remove temporary files =============================================
echo -e "\e[34mCleaning up ...\e[0m"
if [ ${KEEP_SUMMARIES} -eq 0 ] ; then
   rm -f "${SUMMARY_NAME}" "${FLOW_SUMMARY_NAME}"
fi
