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

ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
VERSION=$(awk -F'"' '/^version\s*=/{print $2; exit}' "${ROOT_DIR}/server/Cargo.toml")
TARGET=$(rustc -vV | awk '/^host:/{print $2}')
GIT_SHA=$(git -C "${ROOT_DIR}" rev-parse --short HEAD)
GIT_BRANCH=${BRANCH_NAME:-${GIT_BRANCH:-}}
if [[ -z "${GIT_BRANCH}" ]]; then
  GIT_BRANCH=$(git -C "${ROOT_DIR}" rev-parse --abbrev-ref HEAD 2>/dev/null || echo unknown)
fi
DIST_DIR="${ROOT_DIR}/dist"

mkdir -p "${DIST_DIR}"

echo "Building server (release)..."
cargo build --release --manifest-path "${ROOT_DIR}/server/Cargo.toml"

SERVER_TAR="${DIST_DIR}/lesavka-server-${VERSION}-${TARGET}-${GIT_SHA}.tar.gz"
SERVER_TMP=$(mktemp -d)
install -Dm755 "${ROOT_DIR}/target/release/lesavka-server" "${SERVER_TMP}/lesavka-server"
install -Dm755 "${ROOT_DIR}/scripts/daemon/lesavka-core.sh" "${SERVER_TMP}/lesavka-core.sh"
tar -czf "${SERVER_TAR}" -C "${SERVER_TMP}" lesavka-server lesavka-core.sh
rm -rf "${SERVER_TMP}"

echo "Building client (release)..."
cargo build --release --manifest-path "${ROOT_DIR}/client/Cargo.toml"

CLIENT_TAR="${DIST_DIR}/lesavka-client-${VERSION}-${TARGET}-${GIT_SHA}.tar.gz"
CLIENT_TMP=$(mktemp -d)
install -Dm755 "${ROOT_DIR}/target/release/lesavka-client" "${CLIENT_TMP}/lesavka-client"
tar -czf "${CLIENT_TAR}" -C "${CLIENT_TMP}" lesavka-client
rm -rf "${CLIENT_TMP}"

sha256sum "${SERVER_TAR}" "${CLIENT_TAR}" >"${DIST_DIR}/SHA256SUMS"

PROVENANCE="${DIST_DIR}/lesavka-${VERSION}-${TARGET}-${GIT_SHA}.provenance.json"
cat >"${PROVENANCE}" <<EOF
{
  "suite": "lesavka",
  "version": "${VERSION}",
  "target": "${TARGET}",
  "commit": "${GIT_SHA}",
  "branch": "${GIT_BRANCH}",
  "build_url": "${BUILD_URL:-}",
  "rustc": "$(rustc --version)",
  "cargo": "$(cargo --version)",
  "generated_at_utc": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
}
EOF

echo "Artifacts written to ${DIST_DIR}"
