#!/bin/bash

# ========= 0. 获取脚本所在路径的上一层，设置为 FEP_ENV =========
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
FEP_ENV="$(dirname "$SCRIPT_DIR")"
export FEP_ENV

# ========= 1. 初始化软连接 =========
TEMP_LINK_CREATED=0
# 获取当前路径
CURRENT_DIR=$(pwd)
if [ -L "/FeProject" ]; then
  if [ "$CURRENT_DIR" = "/FeProject" ]; then
    echo "Currently in /FeProject, skipping symlink replacement to avoid issues."
  else
    echo "/FeProject is an existing symlink. Replacing it..."
    sudo rm -f /FeProject
    sudo ln -s "$FEP_ENV" /FeProject
    TEMP_LINK_CREATED=1
    echo "Symlink /FeProject updated."
  fi
elif [ ! -e "/FeProject" ]; then
  echo "/FeProject does not exist. Creating new symlink..."
  sudo ln -s "$FEP_ENV" /FeProject
  TEMP_LINK_CREATED=1
  echo "Symlink /FeProject created."
else
  echo "/FeProject exists but is not a symlink. Please check manually."
fi

if [ -z "$FEP_ENV" ]; then
  echo "Error: FEP_ENV is not set. Please set it first."
  exit 1
fi

# ========= 2. 日志轮转函数 =========
check_log_file() {
  if [ -n "$1" ]; then
    FILE_SIZE=$(du "$1" | awk '{print $1}')
    if [ "$FILE_SIZE" -ge 5120 ]; then
      [ -f "$1.3" ] && rm -f "$1.3"
      [ -f "$1.2" ] && mv "$1.2" "$1.3"
      [ -f "$1.1" ] && mv "$1.1" "$1.2"
      mv "$1" "$1.1"
    fi
  fi
}

LOGFILE="$FEP_ENV/dat/log/start_fe.log"
check_log_file "$LOGFILE"

echo "" ; echo ""
echo "******* $(date "+%F %R:%S") Start Processes *******"
echo "" >>"$LOGFILE"
echo "" >>"$LOGFILE"
echo "******* $(date "+%F %R:%S") Start Processes *******" >>"$LOGFILE"

# ========= 3. 启动流程 =========
RUNTIME_CF_FILE="$FEP_ENV/etc/runtime.cf"

echo "Using config file name: $RUNTIME_CF_FILE"
echo "Using config file name: $RUNTIME_CF_FILE" >>"$LOGFILE"

cd "$FEP_ENV/boot" || exit 1
CURDIR=$(pwd)

while read -r LINE; do
  if [ -n "$LINE" ] && [[ ${LINE:0:1} != "#" ]]; then
    BINPATH=$(echo "$LINE" | awk -F '^' '{print $1}' | grep -o "[^ ]\+\( \+[^ ]\+\)*")
    echo "$BINPATH"
    BIN=$(echo "$LINE" | awk -F '^' '{print $2}' | grep -o "[^ ]\+\( \+[^ ]\+\)*")
    echo "$BIN"
    SPECIAL=$(echo "$LINE" | awk -F '^' '{print $4}' | grep -o "[^ ]\+\( \+[^ ]\+\)*")
    echo "$SPECIAL"
    SLEEPSEC=$(echo "$LINE" | awk -F '^' '{print $5}' | grep -o "[^ ]\+\( \+[^ ]\+\)*")
    echo "$SLEEPSEC"
    STARTFLAG=$(echo "$LINE" | awk -F '^' '{print $7}' | grep -o "[^ ]\+\( \+[^ ]\+\)*")
    echo "$STARTFLAG"
    RESTARTFLAG=$(echo "$LINE" | awk -F '^' '{print $6}' | grep -o "[^ ]\+\( \+[^ ]\+\)*")
    echo "$RESTARTFLAG"

    if [ "$RESTARTFLAG" = "IGNORE_RESTART" ]; then
      CMD_STR="sleep $SLEEPSEC"
      echo "$CMD_STR"
      echo "$CMD_STR" >>"$LOGFILE"
      eval "$CMD_STR"

      CMD_STR="$BINPATH$BIN $SPECIAL"
      echo "$CMD_STR"
      echo "$CMD_STR" >>"$LOGFILE"
      eval "$CMD_STR" &>/dev/null
    fi
  fi
done < "$RUNTIME_CF_FILE"

cd "$CURDIR"

DT=$(date "+%F %R:%S.%N")
echo "*******  ${DT:0:23} Start Processes Succcessfully *******"
echo "*******  ${DT:0:23} Start Processes Succcessfully *******" >>"$LOGFILE"

