#!/bin/bash

ARCHITECTURES=("linux/amd64" "linux/arm64" "darwin/amd64" "darwin/arm64" "windows/amd64")
PROJECT_NAME=$(basename "$(pwd)")

prepare_build() {
    mkdir -p dist build_logs
    if [ ! -f go.mod ]; then
        go mod init "$PROJECT_NAME"
    fi
    go mod tidy
}

build_binary() {
    local os=$1
    local arch=$2
    local output="dist/${PROJECT_NAME}_${os}_${arch}"
    env GOOS=$os GOARCH=$arch go build -o $output . &> "build_logs/${os}_${arch}.log"
    if [ $? -ne 0 ]; then
        echo "Build failed for $os/$arch" >> "build_logs/error.log"
    else
        echo "Build succeeded for $os/$arch"
    fi
    if [ "$os" == "linux" ]; then
        env GOOS=$os GOARCH=$arch CGO_ENABLED=0 go build -a -ldflags '-extldflags "-static"' -o "${output}_static" . &> "build_logs/${os}_${arch}_static.log"
        if [ $? -ne 0 ]; then
            echo "Static build failed for $os/$arch" >> "build_logs/error.log"
        else
            echo "Static build succeeded for $os/$arch"
        fi
    fi
}

main() {
    prepare_build
    for arch in "${ARCHITECTURES[@]}"; do
        IFS="/" read -r os arch <<< "$arch"
        build_binary $os $arch
    done
    echo "Build process completed."
}

main
