#!/bin/bash

prefixtext() {
  infile=$1
  prefix="$2"
  echo "${prefix}// SOURCE: $infile"
  echo "${prefix}R\"__CONFIG__("
  while IFS= read -r line;
  do
    echo "${prefix}$line"
  done < "$infile"
  echo -n "${prefix})__CONFIG__\""
}

gencpp() {
  inf=$1
  outf=$2
  namespace=$3
  func=$4
  if [ ! -e "$inf" ]; then
    echo "$inf does not exist"
    exit 1
  fi
  {
    echo "// Copyright 2021-present Facebook. All Rights Reserved."
    echo "// THIS FILE IS AUTOGENERATED DO NOT MODIFY"
    echo "// GENERATED BY: \`$0 $*\`"
    echo "#include <string>"
    echo "#include <vector>"
    echo "namespace $namespace {"
    if [ -d "$inf" ]; then
      echo "const std::vector<std::string> $func() {"
      echo "  return {"
      for f in "$inf"/*.json; do
        prefixtext "$f" "    "
        echo ","
      done
      echo "  };"
    else
      echo "const std::string $func() {"
      echo -n "  return "
      prefixtext "$inf" "  "
      echo ";"
    fi
    echo "}"
    echo "}"
  } > "$outf"
}

INSTALL_DIR=""
for i in "$@"; do
  case $1 in
    --install_dir=*)
      INSTALL_DIR="${i#*=}"
      shift # past argumen=value
      ;;
    *)
      echo "Unknown positional $1"
      exit 1
      ;;
  esac
done

SRC_DIR=$(dirname "${BASH_SOURCE[0]}")
CONFIG_DIR="./configs"
if [ -d $CONFIG_DIR ]; then
  echo "CONFIG_DIR=$CONFIG_DIR"
elif [ -d "${SRC_DIR}/configs" ]; then
  CONFIG_DIR="${SRC_DIR}/configs"
  echo "CONFIG_DIR=$CONFIG_DIR"
else
  echo "ERROR: $0 needs to be executed in project root containing configs"
  exit 1
fi
OUTPUT_DIR="."
if [ -n "$INSTALL_DIR" ]; then
  OUTPUT_DIR=$INSTALL_DIR
fi

NAMESPACE="rackmonsvc"
gencpp "$CONFIG_DIR/interface/rackmon.conf" "$OUTPUT_DIR/GeneratedRackmonInterfaceConfig.cpp" "$NAMESPACE" getInterfaceConfig
gencpp "$CONFIG_DIR/interface/rackmon_pls.conf" "$OUTPUT_DIR/GeneratedRackmonPlsConfig.cpp" "$NAMESPACE" getRackmonPlsConfig
gencpp "$CONFIG_DIR/register_map" "$OUTPUT_DIR/GeneratedRackmonRegisterMapConfig.cpp" "$NAMESPACE" getRegisterMapConfig
