#!/usr/bin/env bash
set -euo pipefail

#
# Commands
#

MKDIR_P="${MKDIR_P:-mkdir -p}"
GO="${GO:-go}"
TAR="${TAR:-tar}"
ZIP_M="${ZIP_M:-zip -m}"
SHA256SUM="${SHA256SUM:-shasum -a 256}"

#
# Variables
#

ARTIFACTS_DIR="${ARTIFACTS_DIR:-artifacts}"

#
#
#

if [ "$#" -lt 1 ] || [ "$#" -gt 2 ]; then
  echo "usage: $0 <name> [<version>]" >&2
  exit 1
fi

dist_name="$1"
dist_version="${2:-unknown}"

go_os="$( $GO env GOOS )"
go_arch="$( $GO env GOARCH )"

bin_ext=
archive_ext=.tar.xz

if [[ "${go_os}" == "windows" ]]; then
  bin_ext=.exe
  archive_ext=.zip
fi

bin_prefix="${dist_name}-${dist_version}-${go_os}-${go_arch}"
bin="${bin_prefix}${bin_ext}"
archive="${bin_prefix}${archive_ext}"

declare -a go_build_args

if [ -n "${LDFLAGS:-}" ]; then
  go_build_args+=( -ldflags "${LDFLAGS[*]}" )
fi

$MKDIR_P "${ARTIFACTS_DIR}"

echo "dist: ${go_os}/${go_arch}"
echo "dist: GOFLAGS=$( $GO env GOFLAGS )"

( set -x; $GO build "${go_build_args[@]}" -o "${ARTIFACTS_DIR}/${bin}" ./cmd/openbao-plugin-secrets-oauthapp )

(
  cd "${ARTIFACTS_DIR}"

  case "${archive_ext}" in
  .tar.xz)
    ( set -x; $TAR -cJ --remove-files -f "${archive}" "${bin}" )
    ;;
  .zip)
    ( set -x; $ZIP_M -q "${archive}" "${bin}" )
    ;;
  esac

  ( set -x; $SHA256SUM "${archive}" >"${archive}.sha256.asc" )
)
