#!/usr/bin/env murex

project = "github.com/lmorg/murex"

args: args %{
    AllowAdditional: false,
    Flags: %{
        --no-colour:  bool,
        --no-color:   --no-colour,
        --compress:   bool,
        --inc-latest: bool
    }
}
catch {
    err $args[Error]
    exit 1
}

go env GOVERSION -> regexp 'f/([1-9]+\.[0-9]+)/' -> set num goversion
# Please note that versions of go < 1.16 will not be detected due to `go env GOVERSION`
# not existing on earlier versions of `go`

if { $args->[[/Flags/--no-colour]] } then {
    config: set shell color false
    config: set proc force-tty true
}

function compress {
    if { $ARGS.2 } then {
        zip -q $(ARGS.1).zip $ARGS.1
        rm $ARGS.1
    } else {
        gzip $ARGS.1
    }
}

mkdir -p bin

# Platforms supported by the go compiler.
# All 32bit ARM targets will be for ARMv7.
targets = %{
    linux:     [ 386, amd64, arm, arm64 ],
    freebsd:   [ 386, amd64, arm        ],
    openbsd:   [ 386, amd64, arm        ],
    netbsd:    [ 386, amd64, arm        ],
    dragonfly: [      amd64             ],
    darwin:    [      amd64             ],
    solaris:   [      amd64             ],
    plan9:     [ 386, amd64, arm        ],
    windows:   [ 386, amd64, arm        ]
}

# Add support for arm64 on supporting Go releases
if { $goversion >= 1.16 } then {
    $targets -> alter: -m /darwin  %[arm64] -> set targets
    $targets -> alter: -m /freebsd %[arm64] -> set targets
    $targets -> alter: -m /openbsd %[arm64] -> set targets
    $targets -> alter: -m /netbsd  %[arm64] -> set targets
}

if { $goversion >= 1.17 } then {
    $targets -> alter: -m /windows %[arm64] -> set targets
}

status = 0

# Assumes the same version is running this script as the source.
# This is a bad assumption to make and ideally there should be a pre-compiled
# version.
version = ${version --short}

$targets -> formap os cpus {
    $cpus -> foreach arch {
        set ext
        if { $os == "windows" } then { set ext=".exe" }

        try {
            ({BLUE}Building $(os)/$(arch)....{RESET})
            export GOOS=$os
            export GOARCH=$arch
            export GOARM=7
            #export GOFLAGS="-trimpath -modcacherw"

            #if { = `$GOARCH` == `amd64` } then {
            #    export GOFLAGS="$GOFLAGS -buildmode=pie"
            #}

            set bin=./bin/murex-$version-$os-$arch$ext
            go build -o $bin $project
            
            !if { $args->[[/Flags/--compress]] } else { compress $bin $ext }
            
            out "{GREEN}SUCCESSFUL{RESET}"
        }
        catch {
            out "{RED}FAILED{RESET}"
            let status++
        }
    }
}

if { and { $args->[[/Flags/--inc-latest]] } { os posix } } then {
    cd bin
    mkdir -p latest
    g * -> foreach src {
        if { $src != "latest" } then {
            $src -> sed s/-$version// -> set dest
            cp -v $src latest/$dest
        }
    }
    cd ..
}

exit $status