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

VERSION="${1:-}"
if [[ -z "$VERSION" ]]; then
  echo "Usage: $0 <version>"
  echo "Example: $0 1.0.6"
  exit 1
fi

if [[ ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  echo "Version must be semver without 'v' prefix (e.g. 1.0.6)"
  exit 1
fi

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
OUT_DIR="${ROOT_DIR}/dist/${VERSION}"
BIN_NAME="zlh-agent-linux-amd64"
BIN_PATH="${OUT_DIR}/${BIN_NAME}"
SHA_PATH="${BIN_PATH}.sha256"

mkdir -p "${OUT_DIR}"

echo "[build] version=v${VERSION}"
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
  go build \
  -trimpath \
  -ldflags "-s -w -X zlh-agent/internal/version.AgentVersion=v${VERSION}" \
  -o "${BIN_PATH}" \
  "${ROOT_DIR}"

sha256sum "${BIN_PATH}" > "${SHA_PATH}"

echo "[ok] binary: ${BIN_PATH}"
echo "[ok] sha256: ${SHA_PATH}"
