#!/bin/bash

serviceName="db-proxy-server"
basePath=$(pwd)
jarPath="$basePath/db-proxy-server.jar"

# 检查Java是否安装并获取Java路径
function check_java_installed {
  if ! command -v java &> /dev/null
  then
    echo "未找到Java环境，请确保Java已安装并配置在PATH中。"
    exit 1
  fi
}

echo "检查Java环境..."
check_java_installed

# 获取Java可执行文件的路径
javaPath=$(command -v java)

servicePath="/etc/systemd/system/${serviceName}.service"

# 检查服务是否已存在
if [ -f "$servicePath" ]; then
  echo "服务已存在，配置文件路径：$servicePath"
  read -p "是否重新生成配置文件并重启服务？(y/n): " response
  if [ "$response" != "y" ]; then
    echo "已退出。"
    exit 0
  fi
fi

if [ ! -f "$jarPath" ]; then
  echo "目录下不存在jar包：db-proxy-server.jar"
  exit 1
fi

# 创建服务文件
cat <<EOF >"$servicePath"
[Unit]
Description=Java Service - $serviceName
After=network.target network-online.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=$javaPath -jar $jarPath
WorkingDirectory=$basePath
User=root
Restart=on-failure
RestartSec=3

[Install]
WantedBy=multi-user.target
EOF

echo "配置文件已生成并写入：$servicePath"

# 重新加载systemd守护进程，启动和启用服务
systemctl daemon-reload
systemctl start $serviceName
systemctl enable $serviceName

# 等待进度条
echo -n "启动服务中"
for i in {1..10}; do
  echo -n "."
  sleep 1
done
echo "完成"

echo "服务${serviceName}已启动。"
echo "在app/logs下查看服务日志"
echo "执行以下命令查看服务状态: systemctl status $serviceName"

# 显示服务状态
systemctl status $serviceName
