#!/bin/bash

# 定义应用名称和 main 包的相对路径。
# `./` 表示从当前目录（项目根目录）开始寻找，最明确的方式。
APP_NAME="ssync"
MAIN_PACKAGE="./cmd/smart-config-syncer"

# 定义目标平台
PLATFORMS="darwin/amd64 darwin/arm64 linux/amd64 linux/arm64 windows/amd64"

# 清理并创建输出目录
echo "🧹 Cleaning up old builds..."
rm -rf build
mkdir -p build

echo "🚀 Starting builds..."

for platform in $PLATFORMS; do
    GOOS=${platform%/*}
    GOARCH=${platform#*/}
    
    OUTPUT_NAME="$APP_NAME-$GOOS-$GOARCH"
    if [ "$GOOS" = "windows" ]; then
        OUTPUT_NAME="$OUTPUT_NAME.exe"
    fi
    
    echo "Building for $GOOS/$GOARCH..."
    
    # 直接使用最简单的相对路径进行编译
    env GOOS=$GOOS GOARCH=$GOARCH go build -o "build/$OUTPUT_NAME" -ldflags="-s -w" $MAIN_PACKAGE
    
    # 检查上一条命令是否成功
    if [ $? -ne 0 ]; then
        echo "❌ An error has occurred! Aborting the script execution..."
        exit 1
    fi
done

echo "🎉 All builds completed successfully!"