#!/bin/bash
source ../environment.sh

if [ -z "$NETWORK" ]; then
echo "错误: 未找到 NETWORK 环境变量"
exit 1
fi
if [ -z "$XXLJOB_NAME" ]; then
echo "错误: 未找到 XXLJOB_NAME 环境变量"
exit 1
fi
if [ -z "$XXLJOB_IMAGE" ]; then
echo "错误: 未找到 XXLJOB_IMAGE 环境变量"
exit 1
fi
if [ -z "$XXLJOB_PORT" ]; then
echo "错误: 未找到 XXLJOB_PORT 环境变量"
exit 1
fi
if [ -z "$XXLJOB_MEMORY" ]; then
echo "错误: 未找到 XXLJOB_MEMORY 环境变量"
exit 1
fi


# 停止并删除已存在的容器
if docker ps -a | grep -q ${XXLJOB_NAME}; then
    echo "停止并删除已存在的 XXL-Job 容器..."
    docker stop ${XXLJOB_NAME} >/dev/null 2>&1
    docker rm ${XXLJOB_NAME} >/dev/null 2>&1
fi

# 检查 MySQL 是否运行
echo "检查 MySQL 连接..."
docker exec ${MYSQL_NAME} mysqladmin -uroot -p${MYSQL_ROOT_PASSWORD} ping >/dev/null 2>&1 || {
    echo "错误: MySQL 未运行或连接失败，请先启动 MySQL"
    exit 1
}

# 启动 XXL-Job 容器
echo "启动 XXL-Job..."
docker run -d \
    --name ${XXLJOB_NAME} \
    --network $NETWORK \
    --memory $XXLJOB_MEMORY \
    --restart unless-stopped \
    -p ${XXLJOB_PORT}:8080 \
    -e PARAMS=" \
        --spring.datasource.url=jdbc:mysql://${MYSQL_NAME}:3306/xxl_job?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai \
        --spring.datasource.username=root \
        --spring.datasource.password=${MYSQL_ROOT_PASSWORD} \
        --xxl.job.accessToken=${XXLJOB_ACCESS_TOKEN:-default_token} \
        --server.servlet.context-path=/xxl-job-admin" \
    --mount type=bind,source=/etc/localtime,target=/etc/localtime,readonly \
    $XXLJOB_IMAGE

# 等待 XXL-Job 启动
echo "等待 XXL-Job 就绪..."
echo "访问地址: http://localhost:${XXLJOB_PORT}/xxl-job-admin"
echo "默认账号: admin / 123456"


# # 读取变量
# source ../environment.sh
# SERVICE_NAME="xxljob"

# if docker service ls --filter "name=$SERVICE_NAME" | grep -q "$SERVICE_NAME"; then
#     echo "Service $SERVICE_NAME exists. Deleting..."
#     docker service rm  $SERVICE_NAME
# fi
# echo "Service $SERVICE_NAME . Creating..."
# docker service create \
#     --name "$SERVICE_NAME" \
#     -e PARAMS="--xxl.job.accessToken=tuoheng --spring.datasource.url=jdbc:mysql://mysql:3306/xxl_job?Unicode=true&characterEncoding=UTF-8 --spring.datasource.username=root --spring.datasource.password=$MYSQL_ROOT_PASSWORD" \
#     --restart-condition any \
#     --network "$NETWORK" \
#     --publish "8181:8080" \
#     --constraint 'node.role == manager' \
#     xuxueli/xxl-job-admin:2.4.0
# docker service ls
