#!/usr/bin/env bash
#
# build-server.sh — build the production-shaped voicecat-server (+ voicecat-admin)
# and stage the binaries into dist/server/.
#
# Uses the `server-release` CMake preset (Release, stripped, no tests — see
# docs/building.md §5). Works on Windows, Linux, and macOS; the vcpkg triplet
# is auto-resolved by cmake/voicecat-toolchain.cmake.
#
# Usage:
#   scripts/build-server.sh                  # build + stage into ./dist/server
#   scripts/build-server.sh --dist /out      # stage into /out/server
#   scripts/build-server.sh --no-configure   # skip cmake configure, just rebuild + stage
#   scripts/build-server.sh -h|--help        # show this help
#
# Override the default dist dir (<repo>/dist) with --dist or VOICECAT_DIST_DIR.
# Requires VCPKG_ROOT (or a pre-configured build/server-release cache).
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VC_SCRIPT_NAME="build-server"
source "$SCRIPT_DIR/common.sh"

DO_CONFIGURE=true
while [[ $# -gt 0 ]]; do
    case "$1" in
        --dist)         vc_set_dist "$2"; shift 2 ;;
        --no-configure) DO_CONFIGURE=false; shift ;;
        -h|--help)      vc_print_help "$0"; exit 0 ;;
        *) vc_die "unknown arg: $1 (try --help)" ;;
    esac
done

vc_log "dist dir: $VC_DIST_DIR"
vc_resolve_vcpkg_root server-release

vc_step "configure + build (preset: server-release)"
if $DO_CONFIGURE; then
    cmake --preset server-release
fi
cmake --build --preset server-release

BIN_DIR="$VC_REPO_ROOT/build/server-release/bin"
EXE_EXT=""
[[ "$(vc_host_os)" == "windows" ]] && EXE_EXT=".exe"

vc_log "staging binaries -> $VC_DIST_DIR/server"
STAGE="$(vc_dist_subdir server)"

for b in voicecat-server voicecat-admin; do
    f="$BIN_DIR/$b$EXE_EXT"
    if [[ ! -f "$f" ]]; then
        # voicecat-admin only builds when vcpkg deps are on (server-release has
        # them on), so it should exist — but be lenient about admin on odd configs.
        [[ "$b" == "voicecat-admin" ]] && { vc_log "note: $b not found, skipping"; continue; }
        vc_die "expected output not found: $f"
    fi
    cp "$f" "$STAGE/"
    vc_ok "$b$EXE_EXT -> $STAGE/$(basename "$f") ($(vc_file_size "$f") bytes)"
done

vc_ok "done -> $STAGE"
