#!/bin/sh
# script/build: build the `secret` binary into the repo root, with its
# version and git commit stamped in (`secret info` shows both).
set -eu

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

main() {
    cd "$ROOT"
    # CGO is required (Makefile exports this too)
    export CGO_ENABLED=1
    # A VERSION set in the environment wins (`make build VERSION=x`, as
    # the Dockerfile does); otherwise `git describe` of this checkout.
    version="${VERSION:-}"
    if [ -z "$version" ]; then
        version="$(git describe --tags --always --dirty 2>/dev/null ||
            echo dev)"
    fi
    commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)"
    pkg=git.eeqj.de/sneak/secret/internal/cli
    # Build the file, not the package `./cmd/secret`: a package build
    # also stamps git status into the binary and fails where git cannot
    # read the checkout, instead of falling back to `dev`/`unknown`.
    go build -v \
        -ldflags "-X '$pkg.Version=$version' -X '$pkg.GitCommit=$commit'" \
        -o secret cmd/secret/main.go
}

main "$@"
