#!/bin/sh
# script/build: compile the netwatch-server binary into the backend
# project root. Version and architecture are stamped into the binary via
# ldflags; on Linux the binary is statically linked.
set -eu

ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"

BINARY="netwatch-server"

main() {
    cd "$ROOT"

    # git describe fails outside a working repo (e.g. a source tarball),
    # which must not abort the build.
    version="$(git describe --always --dirty 2>/dev/null || echo unknown)"
    buildarch="$(uname -m)"

    ldflags="-X main.Version=$version -X main.Buildarch=$buildarch"
    if [ "$(uname -s)" != "Darwin" ]; then
        ldflags="-linkmode external -extldflags -static $ldflags"
    fi

    go build -o "$BINARY" -ldflags "$ldflags" ./cmd/netwatch-server/
}

main "$@"
