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

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

# 准备 docker run 命令
DOCKER_RUN_CMD="docker run --pull always -d \
--name ${NGINX_NAME} \
--network ${NETWORK} \
-p ${NGINX_HTTP_PORT}:80 \
-p ${NGINX_HTTPS_PORT}:443 \
--env TZ=Asia/Shanghai \
--memory ${NGINX_MEMORY} \
--volume ${STREAM_DATA}:/data/recording \
--volume ${SRS_DATA}:/data/srs"

# 如果配置了证书，添加证书挂载
if [ ! -z "${PEM_PATH}" ] && [ ! -z "${KEY_PATH}" ]; then
    echo "检测到证书配置，将挂载证书文件..."
    if [ ! -f "${PEM_PATH}" ] || [ ! -f "${KEY_PATH}" ]; then
        echo "错误：证书文件不存在！"
        exit 1
    fi
    DOCKER_RUN_CMD="${DOCKER_RUN_CMD} \
--volume ${PEM_PATH}:/etc/nginx/t-aaron.com.pem \
--volume ${KEY_PATH}:/etc/nginx/t-aaron.com.key"
fi
echo "镜像名字------"
echo ${NGINX_IMAGE}

# 添加镜像名称并运行容器
DOCKER_RUN_CMD="${DOCKER_RUN_CMD} ${NGINX_IMAGE}"

# 执行 docker run 命令
echo "启动 Nginx 容器..."
echo ${DOCKER_RUN_CMD}
eval ${DOCKER_RUN_CMD}

# 检查容器是否成功启动
if [ $? -eq 0 ]; then
    echo "Nginx 容器启动成功！"
    docker ps | grep ${NGINX_NAME}
else
    echo "错误：Nginx 容器启动失败！"
    exit 1
fi

 