#!/bin/bash
T2ITrainer_PORT=7860
Tensorboard_PORT=6006
WORK_DIR="/root/T2ITrainer"
T2ITrainer_LOG_FILE="/root/T2ITrainer/logs/t2itrainer.log"
Tensorboard_LOG_FILE="/root/T2ITrainer/logs/tensorboard.log"
PYTHON_CMD="/root/miniconda3/bin/python"
Tensorboard_CMD="/root/miniconda3/bin/tensorboard"

kill_process_by_port() {
    local port=$1
    local service_name=$2

    if ! ss -tln | grep -q ":$port "; then
        echo "$service_name 未在运行"
        return 0
    fi

    echo "$service_name 正在运行，准备关闭..."
    PID=$(ss -tlnp | grep ":$port " | awk '{print $6}' | cut -d',' -f2 | tr -d 'pid=')

    if [ -n "$PID" ]; then
        #kill -9 "$PID" 2>/dev/null || true
	PGID=$(ps -o pgid= -p "$PID" | awk '{print $1}')
        kill -9 -- -"$PGID" 2>/dev/null || true
        sleep 3  # 等待进程完全终止
    fi
    echo "$service_name 关闭完成..."
}

kill_process_by_port $T2ITrainer_PORT "T2ITrainer"
kill_process_by_port $Tensorboard_PORT "TensorBoard"

cd $WORK_DIR
export WANDB_BASE_URL=https://api.bandw.top/
setsid $PYTHON_CMD ui_flux_fill.py >> $T2ITrainer_LOG_FILE 2>&1 &
echo "T2ITrainer 已启动..."

setsid $Tensorboard_CMD --logdir=/root/T2ITrainer/logs --host=0.0.0.0 --port=$Tensorboard_PORT >> $Tensorboard_LOG_FILE 2>&1 &
echo "tensorboard 已启动..."

