#!/bin/bash

# ============================
# 停止旧进程
# ============================
echo ">>> Stopping old process..."
PID=$(ps -ef | grep "api.jar" | grep -v "grep" | awk '{print $2}')
if [ -n "$PID" ]; then
  echo ">>> Killing process ID: $PID"
  kill -9 "$PID"
  sleep 5
else
  echo ">>> No running process found, skipping..."
fi

# ============================
# 启动新版本
# ============================
echo ">>> Starting new version..."
cd /home/program/ || { echo "Directory not found: /home/program"; exit 1; }
nohup java -Xms4096m -Xmx4096m -XX:-UseGCOverheadLimit -jar api.jar --spring.profiles.active=prod >api.out 2>&1 &

# ============================
# 检查启动状态
# ============================
sleep 5
NEW_PID=$(ps -ef | grep "api.jar" | grep -v "grep" | awk '{print $2}')
if [ -n "$NEW_PID" ]; then
  echo ">>> Project started successfully, process ID: $NEW_PID"
else
  echo ">>> Project failed to start, check log: /home/program/api.out"
  exit 1
fi

echo ">>> Deployment completed!"