#!/bin/bash

ARCHITECTURES=("darwin/arm64" "linux/amd64" "linux/arm64" "darwin/amd64" "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_main="dist/${PROJECT_NAME}_${os}_${arch}_main"
    local output_filter="dist/${PROJECT_NAME}_${os}_${arch}_filter"
    local output_api="dist/${PROJECT_NAME}_${os}_${arch}_api"

    env GOOS=$os GOARCH=$arch go build -o $output_main main.go &> "build_logs/${os}_${arch}_main.log"
    if [ $? -ne 0 ]; then
        echo "Build failed for $os/$arch main" >> "build_logs/error.log"
    else
        echo "Build succeeded for $os/$arch main"
    fi

    env GOOS=$os GOARCH=$arch go build -o $output_filter filter.go &> "build_logs/${os}_${arch}_filter.log"
    if [ $? -ne 0 ]; then
        echo "Build failed for $os/$arch filter" >> "build_logs/error.log"
    else
        echo "Build succeeded for $os/$arch filter"
    fi

    env GOOS=$os GOARCH=$arch go build -o $output_api api.go &> "build_logs/${os}_${arch}_api.log"
    if [ $? -ne 0 ]; then
        echo "Build failed for $os/$arch api" >> "build_logs/error.log"
    else
        echo "Build succeeded for $os/$arch api"
    fi

    if [ "$os" == "linux" ]; then
        env GOOS=$os GOARCH=$arch CGO_ENABLED=0 go build -a -ldflags '-extldflags "-static"' -o "${output_main}_static" main.go &> "build_logs/${os}_${arch}_main_static.log"
        if [ $? -ne 0 ]; then
            echo "Static build failed for $os/$arch main" >> "build_logs/error.log"
        else
            echo "Static build succeeded for $os/$arch main"
        fi

        env GOOS=$os GOARCH=$arch CGO_ENABLED=0 go build -a -ldflags '-extldflags "-static"' -o "${output_filter}_static" filter.go &> "build_logs/${os}_${arch}_filter_static.log"
        if [ $? -ne 0 ]; then
            echo "Static build failed for $os/$arch filter" >> "build_logs/error.log"
        else
            echo "Static build succeeded for $os/$arch filter"
        fi

        env GOOS=$os GOARCH=$arch CGO_ENABLED=0 go build -a -ldflags '-extldflags "-static"' -o "${output_api}_static" api.go &> "build_logs/${os}_${arch}_api_static.log"
        if [ $? -ne 0 ]; then
            echo "Static build failed for $os/$arch api" >> "build_logs/error.log"
        else
            echo "Static build succeeded for $os/$arch api"
        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
