#!/usr/bin/env bash
#
# build-all.sh — build every artifact this host can produce and stage it under
# dist/. Convenience wrapper over the per-artifact scripts in scripts/.
#
# On macOS:   server + libs (macOS slice + xcframework) + macos-client (.app)
#             optionally: iOS client for simulator (pass --ios-client)
# On Windows: server + libs (windows DLL) + windows-client (.exe folder)
# On Linux:   server only (no native client presets target Linux)
#
# Usage:
#   scripts/build-all.sh                  # build everything host can, into ./dist
#   scripts/build-all.sh --dist /out
#   scripts/build-all.sh --no-configure   # passed through to each step
#   scripts/build-all.sh --skip-client    # skip the GUI client(s)
#   scripts/build-all.sh --skip-libs      # skip the library artifacts
#   scripts/build-all.sh --skip-server    # skip the server
#   scripts/build-all.sh --ios-client     # also build iOS simulator client (macOS only)
#   scripts/build-all.sh -h|--help
set -euo pipefail

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

PASS_ARGS=()
SKIP_CLIENT=false
SKIP_LIBS=false
SKIP_SERVER=false
BUILD_IOS_CLIENT=false
while [[ $# -gt 0 ]]; do
    case "$1" in
        --dist)         PASS_ARGS+=( --dist "$2" ); vc_set_dist "$2"; shift 2 ;;
        --no-configure) PASS_ARGS+=( --no-configure ); shift ;;
        --skip-client)  SKIP_CLIENT=true; shift ;;
        --skip-libs)    SKIP_LIBS=true; shift ;;
        --skip-server)  SKIP_SERVER=true; shift ;;
        --ios-client)   BUILD_IOS_CLIENT=true; shift ;;
        -h|--help)      vc_print_help "$0"; exit 0 ;;
        *) vc_die "unknown arg: $1 (try --help)" ;;
    esac
done

HOST="$(vc_host_os)"
vc_log "host: $HOST   dist: $VC_DIST_DIR"

run() {
    local name="$1"; shift
    vc_step "→ $name $*"
    "$SCRIPT_DIR/$name" "$@" "${PASS_ARGS[@]}"
}

if ! $SKIP_SERVER; then
    run build-server.sh
fi

if ! $SKIP_LIBS; then
    if [[ "$HOST" == "macos" ]]; then
        run build-libs.sh --platform macos
    elif [[ "$HOST" == "windows" ]]; then
        run build-libs.sh --platform windows
    fi
fi

if ! $SKIP_CLIENT; then
    if [[ "$HOST" == "macos" ]]; then
        run build-macos-client.sh
        $BUILD_IOS_CLIENT && run build-ios-client.sh
    elif [[ "$HOST" == "windows" ]]; then
        run build-windows-client.sh
    fi
fi

vc_ok "all done -> $VC_DIST_DIR"
vc_log "contents:"
( cd "$VC_DIST_DIR" && find . -maxdepth 3 | sort | sed 's/^/    /' ) || true
