##!/bin/sh
# build.sh - 自动化构建Docker镜像脚本
# 用法: ./build.sh <压缩文件>

# 参数验证
if [ $# -ne 1 ]; then
    echo "错误：参数数量不正确"
    echo "用法: $0 <压缩文件>"
    echo "压缩文件名格式应为: Edge_PLCDrv_<架构>_<版本号>.tar.gz"
    exit 1
fi

# 解压参数配置
COMPRESSED_FILE="$1"

# 从文件名提取架构和版本
filename=$(basename "$COMPRESSED_FILE" .tar.gz)
IFS='_' read -ra parts <<< "$filename"

if [ ${#parts[@]} -lt 4 ]; then
    echo "错误：压缩文件名格式不正确"
    echo "应为: Edge_PLCDrv_<架构>_<版本号>.tar.gz"
    exit 1
fi

ARCH_TYPE="${parts[2]}"
VERSION=$(IFS='_'; echo "${parts[*]:3}")
TARGET_DIR="./prog"

# 架构参数验证

# 架构参数验证
if [[ "$ARCH_TYPE" == "arm"  ]]; then
    ARCH_TYPE="arm64"
fi

if [[ "$ARCH_TYPE" != "arm64" && "$ARCH_TYPE" != "amd64" ]]; then
    echo "错误：不支持的架构类型 '$ARCH_TYPE'，仅支持 arm64/amd64"
    exit 1
fi

# 创建目标目录（网页5/7解压目录处理逻辑）
mkdir -p "$TARGET_DIR"

# 解压操作（网页6/7解压命令参考）
echo "正在解压 $COMPRESSED_FILE 到 $TARGET_DIR..."
tar -xzf "$COMPRESSED_FILE" -C "$TARGET_DIR" || {
    echo "解压失败，请检查压缩文件完整性"; 
    exit 1
}

#备份压缩文件
cp $COMPRESSED_FILE $TARGET_DIR/backup.tar.gz

# Docker构建参数配置
declare -A ARCH_CONFIG=(
    ["arm64"]="ARCH32="armhf" linux/arm64"
    ["amd64"]="ARCH32="i386" linux/amd64"
)

# 动态生成镜像标签
#IMAGE_TAG="gitiot.mgm-iot.com/iot_images/edge_${ARCH_TYPE}:v1.0.0"
IMAGE_TAG="swr.cn-north-4.myhuaweicloud.com/cloud-yuzhen/edge_plc_wb_${ARCH_TYPE}:${VERSION}"

# 执行构建命令（网页3/5的Docker参数传递模式）
echo "启动Docker构建（架构：$ARCH_TYPE）..."
BUILDCMD="docker buildx build \
    --build-arg "${ARCH_CONFIG[$ARCH_TYPE]%% *}" \
    --load \
    -t "$IMAGE_TAG" \
    --platform "${ARCH_CONFIG[$ARCH_TYPE]##* }" ."

echo $BUILDCMD
$BUILDCMD || {
    echo "构建失败...";
    exit 1
}

echo "构建完成，镜像已生成：$IMAGE_TAG"
echo "正在推送镜像到镜像仓库..."
# docker push "$IMAGE_TAG"