#!/bin/bash

ARCHITECTURES=("linux/amd64" "linux/arm64" "darwin/amd64" "darwin/arm64" "windows/amd64")
PROJECTS=("main.go:debugreport" "decodereport.go:decodereport")

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

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

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

main
