#!/bin/bash
set -e

version=latest

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"

echo "=========================================="
echo "开始构建 ZLMediaKit Docker 镜像"
echo "=========================================="

# 检查 ZLM 目录是否存在
if [ ! -d "${PROJECT_ROOT}/ZLM" ]; then
    echo "错误: ZLM 目录不存在: ${PROJECT_ROOT}/ZLM"
    exit 1
fi

# 检查 ZLM 源码是否完整
if [ ! -d "${PROJECT_ROOT}/ZLM/3rdpart/ZLToolKit/src" ]; then
    echo "错误: ZLM 源码不完整，请确保 3rdpart 目录下的依赖库存在"
    exit 1
fi

# 清理旧的 ZLM 目录（如果存在）
if [ -d "${SCRIPT_DIR}/ZLM" ]; then
    echo "清理旧的 ZLM 目录..."
    rm -rf "${SCRIPT_DIR}/ZLM"
fi

# 复制 ZLM 目录到 media 目录
echo "复制 ZLM 源码到构建目录..."
cp -r "${PROJECT_ROOT}/ZLM" "${SCRIPT_DIR}/ZLM"

echo "开始构建 Docker 镜像..."

docker build -t polaris-media:${version} .

# 构建完成后清理
echo "清理构建目录..."
rm -rf "${SCRIPT_DIR}/ZLM"

echo "=========================================="
echo "构建完成！"
echo "镜像: polaris-media:${version}"
echo "=========================================="