#!/bin/bash


################################################################################
# Variables                                                                    #
################################################################################
PROD=0
TRIGGER_MIGRATION=0
PRODUCTIVE="productive"
DEVELOPMENT="development"
ENV_MODE=""
DATA_PATH=""
MSII_ALTER_FW_DIR=""
DEFAULT_MODE="ChargeboxControl"
DEFAULT_WORK_DIR="evtec-ecp-data"
FALLBACK_REASON="no -t ('system type') option given, fallback to ChargeboxControl"
MAIN_ARG=""
MAIN_PRIO_CMD_DEV="nice -n -20"
MAIN_CALL_PRODUCTIVE="python3 -u Main.p*"
MAIN_CALL_DEVELOPMENT="python3 -u Main.p*"
TYPE=""
ROLES="ChargeboxControl PowerSinkControl VehicleControl MSIControl ContainerControl HmiControl DCMSControl MeterControl"
declare -a ECP_WORK_DIR_PATH_SUBFOLDERS=("config data debug log media certificates profiling")
declare -a GRAPHICS_SUBFOLDERS=("custom-graphics promotion-screen-graphics")


################################################################################
# Functions                                                                    #
################################################################################
HandleEvtecWorkDir()
{
    # Check if a path in ECP_WORK_FILES_DIR is given
    if [[ -z "$ECP_WORK_FILES_DIR" ]]; then

      # Check if a custom path is given
      if [[ ! -z "$DATA_PATH" ]]; then
        ECP_WORK_FILES_DIR=$DATA_PATH
      else
        # Fallback, current location
        ECP_WORK_FILES_DIR=$PWD/$DEFAULT_WORK_DIR
      fi

      export ECP_WORK_FILES_DIR
   fi
}

CheckApplicationMode()
{
  eval defaultMode="$1"
  eval fallbackReason="$2"
  eval types="$3"

  # Check Main arg, if not set fallback to default ChargeboxControl  
  for POS in ${types[@]}; do
    if [[ $POS == "$TYPE" ]]; then
      MAIN_ARG=$TYPE
    fi
  done
  
  if [[ -z "$MAIN_ARG" ]]; then
    echo $fallbackReason
    MAIN_ARG=$defaultMode
  fi
}

SetStartMode()
{
  # Select how start the application
  if [[ $PROD == 0 ]]; then
    MAIN_CMD="${MAIN_PRIO_CMD_DEV} ${MAIN_CALL_DEVELOPMENT}"
    ENV_MODE=$DEVELOPMENT
  else
    MAIN_CMD=$MAIN_CALL_PRODUCTIVE # to be replaced after sourcecode protection is clear
    ENV_MODE=$PRODUCTIVE
  fi
  export ENV_MODE
}

CreateEvtecFolderStructure()
{
  for subfolder in $ECP_WORK_DIR_PATH_SUBFOLDERS; do
    newpath="${1}"/$subfolder

    if [ ! -d "$newpath" ]; then
      mkdir $newpath -p
      chown xfc:xfc $newpath
    fi

  done
}

CreateGraphicsFolderStructure()
{
  for subfolder in $GRAPHICS_SUBFOLDERS; do
    newpath="${1}"/media/$subfolder

    if [ ! -d "$newpath" ]; then
      mkdir $newpath -p
      chown xfc:xfc $newpath
      chmod 774 $newpath
    fi

  done
}

ParseTimezone()
{
  TIME_ZONE_PARAMETER=.Device.TimeZone
  TIME_ZONE_CONFIGURED=$(jq $TIME_ZONE_PARAMETER $ECP_WORK_FILES_DIR/config/config.json | tr -d \")

  TZ=$TIME_ZONE_CONFIGURED;

  export TZ
}

MigrateConfig()
{
  # Forced migration can be used in case of running ECP from the Dev folder
  # On the other hand, the ConfigMigration.service is only performed after reboot and points on /opt/ECP
  if [[ $TRIGGER_MIGRATION == 1 ]]; then
    # Only perform forced migration if the work directory is not evtec-ecp-data
    if [[ "$ECP_WORK_FILES_DIR" != *"$DEFAULT_WORK_DIR"* ]]; then
      echo "Start forced config migration"
      export PYTHONPATH=$PWD
      python3 $PYTHONPATH/config/migration/migrateConfig*
      # Ensure correct file permissions after migration
      chown xfc:xfc $DATA_PATH/config/*.json
    else
      echo "No forced migration on productive configuration!"
    fi
  fi
}

GatherImageVersions()
{
  result=$(python3 utils/rauc/gatherVersions.p*)
  export EVTEC_IMAGE_VERSIONS=$result
}


################################################################################
# Help                                                                         #
################################################################################
Help()
{
   # Display Help
  echo "This script shall be used to start any of the *Main* roles on the MSI platform."
  echo
  echo "Syntax: run [-t|d|n]"
  echo "options:"
  echo "-d   Sets a specific data directory for the application"
  echo "-h   For help instructions"
  echo "-n   Set integer to adjust niceness"
  echo "-p   Production environment /opt/ECP"
  echo "-t   Run a system type; ChargeboxControl, HmiControl, VehicleControl,....  When omitted *ChargeboxControl* is used."
  echo "-m   Specify alternative path for the MSII firmware files."
  echo "-c   Trigger config migration manually"
  echo "     Because of bad performance, ECP is started with normal scheduling policies at the moment. Instead, the niceness"
  echo "     value is initially lowered to be preferred before other processes running on the system. See DS-195"
  echo "     *chrt --fifo 1*"
}


################################################################################
# Main entry                                                                   #
################################################################################
# run-ecp must be started with sudo rights
if [ "$(whoami)" != "root" ]; then
	sudo ./run-ecp "$@"
	exit
fi

# Parse arguments from the command line
while getopts :hpn:t:d:m:cf opt
do
  case $opt in
    h) Help
       exit
       ;;
    p) PROD=1 # Enable prod mode
       ;;
    n) echo "change niceness by $OPTARG"
       MAIN_PRIO_CMD_DEV="nice -n $OPTARG"
       ;;
    t) echo "option t : ($OPTARG)"
       TYPE="$OPTARG"
       ;;
    d) DATA_PATH="$OPTARG"
       ;;
    m) echo "alternative MSII firmware directory: $OPTARG"
       MSII_ALTER_FW_DIR="$OPTARG"
       export MSII_ALTER_FW_DIR
       ;;
    c) TRIGGER_MIGRATION=1
       echo "Trigger config migration!"
       ;;
    *) echo "option $opt unknown"
      ;;
   esac
done

# Preconditioning the application start - *Warmup 123*
HandleEvtecWorkDir
CreateEvtecFolderStructure $ECP_WORK_FILES_DIR
CreateGraphicsFolderStructure $ECP_WORK_FILES_DIR
CheckApplicationMode $DEFAULT_MODE "\${FALLBACK_REASON}" "\${ROLES}"
SetStartMode
ParseTimezone
MigrateConfig
GatherImageVersions

# Start the application - *The semaphore is green*
echo "ECP starts with: Role=${MAIN_ARG}  PROD=${PROD}  DataPath=${ECP_WORK_FILES_DIR}"
exec $MAIN_CMD $MAIN_ARG
