#!/usr/bin/env bash
# build_stage1.sh — Build Hakorune Stage1 selfhost binary
#
# Purpose
# - Produce a minimal Stage1 (Hakorune selfhost) executable from Nyash/Hako sources.
# - Current target is the Stage1 CLI launcher in lang/src/runner/launcher.hako.
# - This is an initial implementation for Phase 25.1: binary layoutと Stage1 dev bin 用導線のみ。
#
# Output
# - target/selfhost/hakorune (by default)
#
# Env / args
# - HAKORUNE_STAGE1_ENTRY: override Stage1 entry .hako (optional).
# - HAKORUNE_STAGE1_OUT:   override output path (optional).
# - NYASH_LLVM_SKIP_BUILD: set to 1 to skip cargo build in ny_mir_builder.sh when artifacts already exist.
# - Args:
#     --out <path>   : override output path (same as HAKORUNE_STAGE1_OUT).
#     --entry <file> : override entry .hako (same as HAKORUNE_STAGE1_ENTRY).
#     -h|--help      : show usage and exit.
#
set -euo pipefail

usage() {
  cat <<'USAGE'
build_stage1.sh — Build Hakorune Stage1 selfhost binary

Usage:
  tools/selfhost/build_stage1.sh [--out <exe_path>] [--entry <entry.hako>]

Defaults:
  entry .hako : lang/src/runner/launcher.hako
  output exe  : target/selfhost/hakorune

Notes:
  - This script uses the Stage-B + MirBuilder pipeline:
      lang/src/runner/launcher.hako
        → tools/hakorune_emit_mir.sh (Program(JSON v0 → MIR JSON)
        → tools/ny_mir_builder.sh --emit exe
  - The Rust binary (Stage0) is treated as bootstrap and is resolved via
    the existing helpers inside hakorune_emit_mir.sh / ny_mir_builder.sh.
USAGE
}

ROOT="${NYASH_ROOT:-$(cd "$(dirname "$0")/../.." && pwd)}"

ENTRY_DEFAULT="$ROOT/lang/src/runner/launcher.hako"
OUT_DEFAULT="$ROOT/target/selfhost/hakorune"

ENTRY="${HAKORUNE_STAGE1_ENTRY:-$ENTRY_DEFAULT}"
OUT="${HAKORUNE_STAGE1_OUT:-$OUT_DEFAULT}"

while [ $# -gt 0 ]; do
  case "$1" in
    --out)
      OUT="$2"
      shift 2
      ;;
    --entry)
      ENTRY="$2"
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "[stage1] unknown arg: $1" >&2
      usage
      exit 2
      ;;
  esac
done

if [ ! -f "$ENTRY" ]; then
  echo "[stage1] entry .hako not found: $ENTRY" >&2
  exit 2
fi

OUT_DIR="$(dirname "$OUT")"
mkdir -p "$OUT_DIR"

echo "[stage1] building Stage1 selfhost binary" >&2
echo "         entry : $ENTRY" >&2
echo "         output: $OUT" >&2

# Use the Stage‑B → MirBuilder → ny-llvmc path
NYASH_ROOT="$ROOT" bash "$ROOT/tools/selfhost_exe_stageb.sh" "$ENTRY" -o "$OUT"

echo "[stage1] done: $OUT" >&2
