#!/bin/bash
source ../environment.sh
# 检查必要的环境变量
if [ -z "$STREAM_REMOTE_JAR" ]; then
    echo "Error: STREAM_REMOTE_JAR environment variable is not set"
    exit 1
fi

if [ -z "$STREAM_IMAGE" ]; then
    echo "Error: STREAM_IMAGE environment variable is not set"
    exit 1
fi

if [ -z "$STREAM_JAR" ]; then
    echo "Error: STREAM_JAR environment variable is not set"
    exit 1
fi

# 创建临时构建目录
BUILD_DIR=$(mktemp -d)
trap 'rm -rf "$BUILD_DIR"' EXIT

# 复制JAR文件
echo "Copying JAR file from $STREAM_REMOTE_JAR"
cp "$STREAM_REMOTE_JAR" "$BUILD_DIR/${STREAM_JAR}"

# 检查JAR文件是否复制成功
if [ ! -f "$BUILD_DIR/${STREAM_JAR}" ]; then
    echo "Error: Failed to copy JAR file"
    exit 1
fi

# 创建Dockerfile
cat > "$BUILD_DIR/Dockerfile" << EOF
FROM registry.t-aaron.com/tuoheng/ffmpeg:latest

# 设置工作目录
WORKDIR /app

# 设置时区
ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/\$TZ /etc/localtime && echo \$TZ > /etc/timezone

# 创建数据目录
RUN mkdir -p /data/temp && chmod 777 /data/temp
# 创建数据目录
RUN mkdir -p /data/recording && chmod 777 /data/recording
# 创建数据目录
RUN mkdir -p /data/record && chmod 777 /data/record

# 复制JAR文件
COPY ${STREAM_JAR} /app/

# 设置启动命令
ENTRYPOINT ["java", "-jar", "/app/${STREAM_JAR}"]
EOF

# 构建Docker镜像
echo "Building Docker image: $STREAM_IMAGE"
docker build -t "$STREAM_IMAGE" "$BUILD_DIR"

# 清理
# rm -rf "$BUILD_DIR"

echo "Docker image $STREAM_IMAGE has been built successfully"

docker push $STREAM_IMAGE