#!/bin/bash

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

# ========= 1. 初始化软连接 =========
TEMP_LINK_CREATED=0
if [ ! -L "/FeProject" ]; then
  if [ ! -e "/FeProject" ]; then
    sudo ln -s "$FEP_ENV" /FeProject
    TEMP_LINK_CREATED=1
    echo "Temporary symlink /FeProject created."
  else
    echo "/FeProject exists but is not a symlink. Please check manually."
  fi
fi

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

RUNTIME_CF_FILE="$FEP_ENV/etc/runtime.cf"

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

#			if [ "`echo $STARTFLAG`" != "IGNORE_START" ]; then
				CMD_STR="  ps -w | grep `echo "'"``echo $BIN``echo "'"` | grep -v 'grep'"
				BIN2=`echo $BIN` 
				ps -ef | grep "$BIN2" | grep -v 'grep'
#			fi
		fi
	fi		
done < $RUNTIME_CF_FILE

# ========= 4. 清理软链接（仅在本次脚本中创建） =========
if [ "$TEMP_LINK_CREATED" -eq 1 ]; then
  if [ -L "/FeProject" ]; then
    sudo rm -f /FeProject
    echo "Temporary symlink /FeProject removed."
  fi
fi
