#!/bin/bash

# 定义变量
WORK_DIR="/data/sensor"
FILE_PATH=`pwd`
JAR_PATH="$FILE_PATH/iot-local.jar"
RUN_JAR_PATH="$WORK_DIR/iot-local.jar"
SERVICE_FILE="/etc/systemd/system/iot-local.service"
JAVA_EXEC="/usr/bin/java"

# 检查 JAR 文件是否存在
if [ ! -f "$JAR_PATH" ]; then
   echo "JAR file is not exist: $JAR_PATH"
   exit 1
fi

if [ ! -d $WORK_DIR ]; then
    # 如果目录不存在，创建目录
    mkdir -p $WORK_DIR
    echo "mkdir $WORK_DIR success."
else
    echo "$WORK_DIR is exists."
fi
# 复制文件
cp -f $FILE_PATH/*.jar $WORK_DIR/
cp -f $FILE_PATH/*.properties $WORK_DIR/

# 创建 systemd 服务文件
echo "create systemd file: $SERVICE_FILE"
cat <<EOF | sudo tee $SERVICE_FILE
[Unit]
Description=IoT Local Java Application

[Service]
User=root
WorkingDirectory=$WORK_DIR
ExecStart=$JAVA_EXEC -Xmx2g -jar $RUN_JAR_PATH
SuccessExitStatus=143
TimeoutStopSec=10
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

# 重新加载 systemd 配置
echo "reload systemd "
sudo systemctl daemon-reload

# 启动服务
echo "start service"
sudo systemctl start iot-local.service

# 启用开机自启
echo "Boot-time autostart"
sudo systemctl enable iot-local.service

echo "iot-local service running and set Boot-time autostart。"