#!/bin/bash
set -ex

# 从versions.mk读取版本信息
PACKAGE_VERSION=$(grep '^LIB_VERSION :=' versions.mk | awk '{print $3}')
PACKAGE_REVISION=$(grep '^PACKAGE_REVISION :=' versions.mk | awk '{print $3}')
if [ -z "$PACKAGE_VERSION" ] || [ -z "$PACKAGE_REVISION" ]; then
    echo "Error: 无法从versions.mk读取版本信息" >&2
    exit 1
fi

# 解压并安装Go工具链，添加错误处理
unzip -q v0.0.1-go1.24.6.linux-amd64.zip || { echo "Error: 解压Go工具链失败" >&2; exit 1; }
# 使用-T选项确保目录正确替换而非嵌套
if [ -d /usr/local/go ];then
   rm -rf /usr/local/go
fi

mv -T golang.org/toolchain@v0.0.1-go1.24.6.linux-amd64/ /usr/local/go || { echo "Error: 移动Go工具链失败" >&2; exit 1; }
export PATH=/usr/local/go/bin:$PATH

make cmds
source=("dcu-container-runtime" "dcu-cdi-hook" "dcu-ctk" "dcu-docker")
for file in "${source[@]}"
do
   rm -rf SOURCES/$file > /dev/null 2>&1
   cp -r $file SOURCES/$file
done
cp -rf packaging/rpm/SOURCES/* SOURCES/ > /dev/null 2>&1
# 使用现代命令替换语法，提高可读性
GIT_COMMIT=$(git describe --match="" --dirty --long --always --abbrev=40 2> /dev/null || echo "")
PKG_VERS="$PACKAGE_VERSION"
PKG_REV="$PACKAGE_REVISION"
if [ ! -d dist ];then
   mkdir dist
fi
arch=$(uname -m) && \
    rpmbuild --clean --target="$arch" -bb \
             -D "_topdir $PWD" \
             -D "release_date $(date +'%a %b %d %Y')" \
             -D "git_commit ${GIT_COMMIT}" \
             -D "version ${PKG_VERS}" \
             -D "release ${PKG_REV}" \
             packaging/rpm/SPECS/dcu-container-toolkit.spec && \
    # 检查并移动RPM包，添加错误提示
    mv RPMS/"$arch"/*.rpm dist || { echo "Error: 未找到生成的RPM包" >&2; exit 1; }
