#!/bin/bash

set -e

PROCESS_NAME=$1
START_COMMAND="./${PROCESS_NAME}"
LAUNCH_TIME=$(date '+%Y-%m-%d_%H%M%S')

if [[ -z $1 ]]; then
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] 缺少可执行文件参数"
    exit 0
fi

if [ $# -eq 2 ]; then
    START_COMMAND="./${PROCESS_NAME} $2"
fi

if [ $# -ge 3 ]; then
    START_COMMAND="./${PROCESS_NAME} $2 $3"
fi

if [ ! -d "logs" ]; then
    mkdir logs
fi

find logs -type f -ctime +30 -exec rm -f {} \;
rm -f mq.log

# 日志函数
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> logs/running_${LAUNCH_TIME}.log 2>&1 &
}

[ -n "$MQTT_ADDR" ] && export MQTT_ADDR
[ -n "$MQTT_USER" ] && export MQTT_USER
[ -n "$MQTT_PASS" ] && export MQTT_PASS

count=$(ps -ef|grep ${PROCESS_NAME} | grep -v "daemon_run" |grep -v grep|wc -l)
if [ "$count" -gt 0 ]; then
    log "检测到进程 '$PROCESS_NAME' 已存在（数量: $count), 准备重启该进程"
    
    ps -ef|grep ${PROCESS_NAME} | grep -v "daemon_run" |grep -v grep|awk '{print $2}'|xargs -I{} kill -9 {}
    sleep 3
    
    [ ! -x "$PROCESS_NAME" ] && chmod +x "$PROCESS_NAME"
    
    # 启动进程（后台运行，不占用终端）
    echo "####################################################" >> logs/running_${LAUNCH_TIME}.log 2>&1 &
    nohup sh -c "$START_COMMAND" >> "logs/running_${LAUNCH_TIME}.log" 2>&1 &
    echo "$START_COMMAND"
    
    # 等待并验证是否启动成功
    sleep 5
    new_count=$(ps -ef|grep ${PROCESS_NAME} | grep -v "daemon_run" |grep -v grep|wc -l)
    if [ "$new_count" -gt 0 ]; then
        log "进程启动成功，当前数量: $new_count"
    else
        log "警告：启动失败，进程数量仍为 0"
    fi
fi

while true; do
    # 获取进程数量（精确匹配进程名）
    count=$(ps -ef|grep ${PROCESS_NAME} | grep -v "daemon_run" |grep -v grep|wc -l)
    
    if [ "$count" -eq 0 ]; then
        log "检测到进程 '$PROCESS_NAME' 不存在（数量: 0), 正在启动..."
        
        [ ! -x "$PROCESS_NAME" ] && chmod +x "$PROCESS_NAME"
        
        # 启动进程（后台运行，不占用终端）
        echo "####################################################" >> logs/running_${LAUNCH_TIME}.log 2>&1 &
        nohup sh -c "$START_COMMAND" >> "logs/running_${LAUNCH_TIME}.log" 2>&1 &
        echo "$START_COMMAND"
        
        # 等待并验证是否启动成功
        sleep 3
        new_count=$(ps -ef|grep ${PROCESS_NAME} | grep -v "daemon_run" |grep -v grep|wc -l)
        if [ "$new_count" -gt 0 ]; then
            log "进程启动成功，当前数量: $new_count"
        else
            log "警告：启动失败，进程数量仍为 0"
        fi
    fi
    
    sleep 5
done

# 山东高速物流 /bin/bash daemon_run.sh application_ros_bin shandong_wuliu veh01
: <<'COMMENT'
# 相机触发
gnome-terminal --title="trigger-camera" --tab -- bash -c \
"sudo tztek-jetson-tool-internal-trigger-camera /dev/ttyTHS1 30 1000 >/dev/null; exec bash"
sleep 1

# 平台通信
gnome-terminal --title="application_ros_bin" --tab --working-directory=$HOME/enjoydriving/app_ros_bin \
-- bash -c "/bin/bash daemon_run.sh application_ros_bin shandong_wuliu veh01; exec bash"
sleep 1
COMMENT

# 新疆巡检 /bin/bash daemon_run.sh application_ros_bin xinjiang_xunjian syc001
: <<'COMMENT'
# 平台通信
gnome-terminal --title="application_ros_bin" --tab --working-directory=$HOME/enjoydriving/app_ros_bin \
-- bash -c "/bin/bash daemon_run.sh application_ros_bin xinjiang_xunjian syc001; exec bash"
sleep 1
COMMENT

# 云南高速巡检
: <<'COMMENT'
# 平台通信
gnome-terminal --title="application_ros_bin" --tab --working-directory=$HOME/enjoydriving/app_ros_bin \
-- bash -c "/bin/bash daemon_run.sh application_ros_bin yunnan_gaosu syc003; exec bash"
sleep 1
COMMENT

# 歌尔物流
: <<'COMMENT'
# 平台通信
gnome-terminal --title="application_ros_bin" --tab --working-directory=$HOME/enjoydriving/app_ros_bin \
-- bash -c "/bin/bash daemon_run.sh application_ros_bin geer_wuliu veh01; exec bash"
sleep 1
COMMENT
