source ../environment.sh

if [ -z "$NETWORK" ]; then
echo "错误: 未找到 NETWORK 环境变量"
exit 1
fi
if [ -z "$SRS_NAME" ]; then
echo "错误: 未找到 SRS_NAME 环境变量"
exit 1
fi
if [ -z "$SRS_IMAGE" ]; then
echo "错误: 未找到 SRS_IMAGE 环境变量"
exit 1
fi
if [ -z "$SRS_MEMORY" ]; then
echo "错误: 未找到 SRS_MEMORY 环境变量"
exit 1
fi
if [ -z "$SRS_RTMP_PORT" ]; then
echo "错误: 未找到 SRS_RTMP_PORT 环境变量"
exit 1
fi

if [ -z "$SRS_RTC_PORT" ]; then
echo "错误: 未找到 SRS_RTC_PORT 环境变量"
exit 1
fi
if [ -z "$SRS_DATA" ]; then
echo "错误: 未找到 SRS_DATA 环境变量"
exit 1
fi

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

# 在容器内检查并创建必要的目录结构
echo "检查SRS目录结构..."
docker run --rm \
    -v "${SRS_DATA}:/usr/local/srs/objs/nginx/html" \
    $SRS_IMAGE \
    /bin/sh -c '
        if [ -d "/usr/local/srs/objs/nginx/html/record" ]; then
            echo "record目录已存在，跳过创建"
        else
            echo "创建record目录..."
            mkdir -p /usr/local/srs/objs/nginx/html/record
        fi
    '

# 启动SRS容器
# 启动SRS容器 默认也有8080端口
docker run -d \
    --name ${SRS_NAME} \
    --network $NETWORK \
    --memory $SRS_MEMORY \
    --restart unless-stopped \
    -p ${SRS_RTMP_PORT}:1935 \
    -p ${SRS_RTC_PORT}:8000/udp \
    -v "$(pwd)/volumes/srs/conf/srs.conf:/usr/local/srs/conf/docker.conf" \
    -v "${SRS_DATA}:/usr/local/srs/objs/nginx/html" \
    --mount type=bind,source=/etc/localtime,target=/etc/localtime,readonly \
    $SRS_IMAGE
