# Copyright (c) 2026 ttldtor.
# SPDX-License-Identifier: BSL-1.0
# Build and package one immutable source revision. Never remove or reuse directories.
cmake_minimum_required(VERSION 3.24)

# Script-mode help must not validate paths, discover tools or create artifacts.
if(HELP)
  message([=[Usage: cmake -DHELP=ON -P tools/package/bundle.cmake
       cmake -DSOURCE_DIR=<checkout> -DWORK_DIR=<new-dir> -DOUTPUT_ARCHIVE=<new-file> [options] -P tools/package/bundle.cmake
Build and verify a runnable x64 Release SDK bundle from committed source.
Required:
  SOURCE_DIR       Absolute existing committed Git checkout.
  WORK_DIR         New absolute staging directory outside SOURCE_DIR.
  OUTPUT_ARCHIVE   New absolute .zip (Windows) or .tar.gz (Linux), outside WORK_DIR.
Optional -D settings:
  SOURCE_REVISION=HEAD   Git revision resolved to a commit; excludes uncommitted edits.
  GENERATOR=Ninja       CMake generator.
  PARALLEL=2            Positive integer build parallelism (no explicit upper bound).
  MSVC_RUNTIME_LIBRARY=MultiThreaded  Windows: MultiThreaded or MultiThreadedDLL.
  CXX_COMPILER, C_COMPILER, MAKE_PROGRAM  Explicit CMake tool paths; otherwise discovered.
  PYTHON_EXECUTABLE     Optional interpreter for extra HTML-link checks; omitted means that gate is not_run.
                        Documentation builds independently require Python.
  HELP=OFF              ON prints this usage and returns without validation or writes.
Requires CMake >=3.24, Git, native x64 compiler, Doxygen/documentation dependencies,
Python, dumpbin (Windows) or ldd (Linux), and the selected build tool.
Effects: archives Git source, configures/builds/installs Release examples and docs,
runs bundle checks, writes staging evidence and the archive; staging is preserved.
Does not publish or modify Git history. Exit 0 on success/help; nonzero on failure.
Example: cmake -DSOURCE_DIR=C:/src/portals -DWORK_DIR=C:/stage/new -DOUTPUT_ARCHIVE=C:/out/portals.zip -P tools/package/bundle.cmake
]=])
  return()
endif()
include("${CMAKE_CURRENT_LIST_DIR}/common.cmake")

foreach(required IN ITEMS SOURCE_DIR WORK_DIR OUTPUT_ARCHIVE)
  if(NOT DEFINED ${required} OR "${${required}}" STREQUAL "")
    message(FATAL_ERROR "Bundle requires ${required}; see docs/package.md")
  endif()
endforeach()
if(NOT IS_ABSOLUTE "${SOURCE_DIR}" OR NOT IS_DIRECTORY "${SOURCE_DIR}")
  message(FATAL_ERROR "SOURCE_DIR must be an absolute committed Git checkout")
endif()
file(REAL_PATH "${SOURCE_DIR}" SOURCE_DIR)
bundleRequireNewPath(WORK_DIR)
bundleRequireNewPath(OUTPUT_ARCHIVE)
bundlePathIsInside("${SOURCE_DIR}" "${WORK_DIR}" insideSource)
if(insideSource)
  message(FATAL_ERROR "WORK_DIR must be outside SOURCE_DIR")
endif()
bundlePathIsInside("${WORK_DIR}" "${OUTPUT_ARCHIVE}" outputInsideWork)
if(outputInsideWork)
  message(FATAL_ERROR "OUTPUT_ARCHIVE must be outside WORK_DIR")
endif()
if(NOT CMAKE_HOST_SYSTEM_NAME MATCHES "^(Windows|Linux)$")
  message(FATAL_ERROR "Runnable bundles support Windows and Linux hosts only")
endif()
if(NOT DEFINED SOURCE_REVISION)
  set(SOURCE_REVISION HEAD)
endif()
if(NOT DEFINED GENERATOR)
  set(GENERATOR Ninja)
endif()
if(NOT DEFINED PARALLEL)
  set(PARALLEL 2)
endif()
if(NOT PARALLEL MATCHES "^[1-9][0-9]*$")
  message(FATAL_ERROR "PARALLEL must be a positive integer")
endif()
if(CMAKE_HOST_WIN32)
  set(platform windows)
  set(extension .exe)
  if(NOT OUTPUT_ARCHIVE MATCHES "\\.zip$")
    message(FATAL_ERROR "Windows OUTPUT_ARCHIVE must end in .zip")
  endif()
  if(NOT DEFINED MSVC_RUNTIME_LIBRARY)
    set(MSVC_RUNTIME_LIBRARY MultiThreaded)
  endif()
  if(NOT MSVC_RUNTIME_LIBRARY MATCHES "^(MultiThreaded|MultiThreadedDLL)$")
    message(FATAL_ERROR "Release MSVC_RUNTIME_LIBRARY must be MultiThreaded or MultiThreadedDLL")
  endif()
  find_program(DEPENDENCY_INSPECTOR NAMES dumpbin REQUIRED)
else()
  set(platform linux)
  set(extension "")
  set(MSVC_RUNTIME_LIBRARY not-applicable)
  if(NOT OUTPUT_ARCHIVE MATCHES "\\.tar\\.gz$")
    message(FATAL_ERROR "Linux OUTPUT_ARCHIVE must end in .tar.gz")
  endif()
  find_program(DEPENDENCY_INSPECTOR NAMES ldd REQUIRED)
endif()
find_program(GIT_EXECUTABLE NAMES git REQUIRED)
execute_process(COMMAND "${GIT_EXECUTABLE}" -C "${SOURCE_DIR}" rev-parse --verify --end-of-options
  "${SOURCE_REVISION}^{commit}" RESULT_VARIABLE gitResult OUTPUT_VARIABLE commit OUTPUT_STRIP_TRAILING_WHITESPACE)
if(NOT gitResult EQUAL 0 OR NOT commit MATCHES "^[0-9a-f]+$")
  message(FATAL_ERROR "Cannot resolve SOURCE_REVISION to a committed source")
endif()

# The new snapshot has no Git metadata, ignored/private files or working-tree edits.
file(MAKE_DIRECTORY "${WORK_DIR}/source")
set(source "${WORK_DIR}/source")
set(build "${WORK_DIR}/build")
set(bundleName "portals-mvp-${platform}-x64-release")
set(payload "${WORK_DIR}/${bundleName}")
bundleRun("${GIT_EXECUTABLE}" -C "${SOURCE_DIR}" archive --format=tar
  "--output=${WORK_DIR}/source.tar" "${commit}")
file(ARCHIVE_EXTRACT INPUT "${WORK_DIR}/source.tar" DESTINATION "${source}")
if(EXISTS "${source}/.work" OR EXISTS "${source}/.git")
  message(FATAL_ERROR "Source archive unexpectedly contains private or Git state")
endif()
file(SHA256 "${WORK_DIR}/source.tar" sourceArchiveHash)
foreach(required IN ITEMS CMakeLists.txt LICENSE.txt docs/limitations.md
    tools/package/common.cmake tools/package/GETTING-STARTED.md tests/bundle_smoke.cmake)
  if(NOT EXISTS "${source}/${required}")
    message(FATAL_ERROR "Selected revision lacks bundle input: ${required}; commit tooling before packaging")
  endif()
endforeach()
set(configureArgs -S "${source}" -B "${build}" -G "${GENERATOR}"
  -DCMAKE_BUILD_TYPE=Release -DPORTALS_BUILD_TESTS=ON -DPORTALS_BUILD_EXAMPLES=ON
  -DPORTALS_BUILD_TOOLS=OFF -DPORTALS_BUILD_DOCS=ON -DPORTALS_BUILD_FUZZERS=OFF)
if(CMAKE_HOST_WIN32)
  list(APPEND configureArgs "-DCMAKE_MSVC_RUNTIME_LIBRARY=${MSVC_RUNTIME_LIBRARY}")
endif()
foreach(setting IN ITEMS CXX_COMPILER C_COMPILER MAKE_PROGRAM)
  if(DEFINED ${setting} AND NOT "${${setting}}" STREQUAL "")
    list(APPEND configureArgs "-DCMAKE_${setting}=${${setting}}")
  endif()
endforeach()
bundleRun("${CMAKE_COMMAND}" ${configureArgs})
file(GLOB compilerInfo "${build}/CMakeFiles/*/CMakeCXXCompiler.cmake")
list(LENGTH compilerInfo compilerCount)
if(NOT compilerCount EQUAL 1)
  message(FATAL_ERROR "Expected exactly one generated C++ compiler record")
endif()
include("${compilerInfo}")
file(GLOB cCompilerInfo "${build}/CMakeFiles/*/CMakeCCompiler.cmake")
list(LENGTH cCompilerInfo cCompilerCount)
if(NOT cCompilerCount EQUAL 1)
  message(FATAL_ERROR "Expected exactly one generated C compiler record")
endif()
include("${cCompilerInfo}")
if(CMAKE_HOST_WIN32 AND NOT CMAKE_C_COMPILER_ID STREQUAL "MSVC")
  message(FATAL_ERROR "Windows runnable SDK requires MSVC for its C dependency as well")
endif()
if(NOT CMAKE_CXX_SIZEOF_DATA_PTR EQUAL 8)
  message(FATAL_ERROR "Bundle requires a native x64 compiler (pointer size 8)")
endif()
if(CMAKE_HOST_WIN32 AND NOT CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
  message(FATAL_ERROR "Windows runnable bundle requires MSVC")
endif()
if(CMAKE_CXX_COMPILER_ARCHITECTURE_ID AND
    NOT CMAKE_CXX_COMPILER_ARCHITECTURE_ID MATCHES "^(x64|x86_64|X86_64|AMD64|amd64)$")
  message(FATAL_ERROR "Bundle requires x64, found ${CMAKE_CXX_COMPILER_ARCHITECTURE_ID}")
endif()
cmake_host_system_information(RESULT hostArchitecture QUERY OS_PLATFORM)
if(NOT hostArchitecture MATCHES "^(AMD64|amd64|x86_64|X86_64)$")
  message(FATAL_ERROR "Bundle requires an x64 host, found ${hostArchitecture}")
endif()
bundleRun("${CMAKE_COMMAND}" --build "${build}" --config Release --parallel "${PARALLEL}"
  --target portals_dashboard portals_gallery portals_custom_widget portals_editor_history portals_click_handlers portals_docs)
file(MAKE_DIRECTORY "${payload}/bin" "${payload}/docs/html" "${payload}/install"
  "${payload}/examples/external-consumer" "${payload}/licenses" "${payload}/data")
bundleRun("${CMAKE_COMMAND}" --install "${build}" --config Release --prefix "${payload}/install")
file(COPY "${build}/docs/html/" DESTINATION "${payload}/docs/html")
file(COPY "${source}/examples/" DESTINATION "${payload}/examples/source")
bundleStageConsumer("${source}" "${payload}/examples/external-consumer")
file(COPY "${source}/themes" DESTINATION "${payload}")
file(COPY "${source}/tests/fixtures/traces" DESTINATION "${payload}/data")
file(COPY "${source}/examples/replay/data.hpp" DESTINATION "${payload}/data")
file(COPY "${source}/tools/package/data-README.md" DESTINATION "${payload}/data")
file(COPY "${source}/LICENSE.txt" "${source}/vendor/utf8proc/LICENSE.md"
  "${source}/tests/fixtures/unicode/Unicode-LICENSE.txt" DESTINATION "${payload}/licenses")
configure_file("${source}/vendor/textual/LICENSE" "${payload}/licenses/textual-LICENSE.txt" COPYONLY)
configure_file("${source}/vendor/lyra/LICENSE.txt" "${payload}/licenses/lyra-LICENSE.txt" COPYONLY)
configure_file("${source}/vendor/monocypher/LICENCE.md" "${payload}/licenses/monocypher-LICENCE.md" COPYONLY)
file(COPY "${source}/docs/limitations.md" DESTINATION "${payload}/docs")
file(COPY "${source}/tools/package/GETTING-STARTED.md" DESTINATION "${payload}")
file(COPY "${source}/tools/package/run.ps1" "${source}/tools/package/run.sh" DESTINATION "${payload}")
file(CHMOD "${payload}/run.sh" PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE)
file(COPY "${source}/tools/package/common.cmake" DESTINATION "${payload}/verify")
file(COPY "${source}/tests/bundle_smoke.cmake" DESTINATION "${payload}/verify")
file(COPY "${source}/tools/docs/check_links.py" DESTINATION "${payload}/verify")

set(imports "{}")
set(examples "{}")
set(exampleDirectories dashboard gallery custom_widget editor_history click_handlers)
set(examplePrograms portals_dashboard portals_gallery portals_custom_widget portals_editor_history portals_click_handlers)
foreach(index RANGE 0 4)
  list(GET exampleDirectories ${index} directory)
  list(GET examplePrograms ${index} program)
  set(executable "${build}/examples/${directory}/${program}${extension}")
  if(NOT EXISTS "${executable}")
    set(executable "${build}/examples/${directory}/Release/${program}${extension}")
  endif()
  if(NOT EXISTS "${executable}")
    message(FATAL_ERROR "Built Release example missing: ${program}")
  endif()
  file(COPY "${executable}" DESTINATION "${payload}/bin")
  if(CMAKE_HOST_WIN32)
    set(inspectArgs /DEPENDENTS "${payload}/bin/${program}${extension}")
  else()
    set(inspectArgs "${payload}/bin/${program}")
  endif()
  execute_process(COMMAND "${DEPENDENCY_INSPECTOR}" ${inspectArgs} RESULT_VARIABLE result
    OUTPUT_VARIABLE dependencyOutput ERROR_VARIABLE dependencyError)
  if(NOT result EQUAL 0)
    message(FATAL_ERROR "Dependency inspection failed for ${program}: ${dependencyError}")
  endif()
  string(TOLOWER "${dependencyOutput}" lowerDependencies)
  if(CMAKE_HOST_WIN32 AND MSVC_RUNTIME_LIBRARY STREQUAL "MultiThreaded" AND
      lowerDependencies MATCHES "(vcruntime|msvcp[0-9]|ucrtbase|api-ms-win-crt)")
    message(FATAL_ERROR "Static CRT requested but dynamic CRT import found in ${program}: ${dependencyOutput}")
  endif()
  bundleJsonQuote(quotedImports "${dependencyOutput}")
  bundleJsonQuote(quotedProgram "bin/${program}${extension}")
  string(JSON imports SET "${imports}" "${program}" "${quotedImports}")
  string(JSON examples SET "${examples}" "${directory}" "${quotedProgram}")
endforeach()

set(linkStatus not_run)
if(DEFINED PYTHON_EXECUTABLE AND NOT PYTHON_EXECUTABLE STREQUAL "")
  bundleRun("${PYTHON_EXECUTABLE}" "${payload}/verify/check_links.py" "${payload}/docs/html")
  set(linkStatus passed)
endif()
if(CMAKE_HOST_UNIX)
  execute_process(COMMAND "${DEPENDENCY_INSPECTOR}" --version RESULT_VARIABLE result
    OUTPUT_VARIABLE libcVersion ERROR_VARIABLE libcError)
  if(NOT result EQUAL 0)
    message(FATAL_ERROR "Cannot record ldd/libc version: ${libcError}")
  endif()
else()
  set(libcVersion "not-applicable; Windows DLL imports recorded per executable")
endif()
cmake_host_system_information(RESULT osName QUERY OS_NAME)
cmake_host_system_information(RESULT osRelease QUERY OS_RELEASE)
set(manifest "{\"schema_version\":1}")
foreach(field IN ITEMS commit sourceArchiveHash platform osName osRelease CMAKE_CXX_COMPILER
    CMAKE_CXX_COMPILER_ID CMAKE_CXX_COMPILER_VERSION CMAKE_C_COMPILER CMAKE_C_COMPILER_ID
    CMAKE_C_COMPILER_VERSION MSVC_RUNTIME_LIBRARY libcVersion GENERATOR linkStatus)
  bundleJsonQuote(value "${${field}}")
  string(JSON manifest SET "${manifest}" "${field}" "${value}")
endforeach()
set(flags "{}")
file(STRINGS "${build}/CMakeCache.txt" flagLines REGEX "^CMAKE_(C|CXX)_FLAGS(_RELEASE)?:STRING=")
foreach(line IN LISTS flagLines)
  string(REGEX REPLACE ":STRING=.*$" "" key "${line}")
  string(REGEX REPLACE "^[^=]*=" "" flagValue "${line}")
  bundleJsonQuote(value "${flagValue}")
  string(JSON flags SET "${flags}" "${key}" "${value}")
endforeach()
string(JSON manifest SET "${manifest}" build_flags "${flags}")
string(JSON manifest SET "${manifest}" configuration "\"Release\"")
string(JSON manifest SET "${manifest}" architecture "\"x64\"")
string(JSON manifest SET "${manifest}" dependency_imports "${imports}")
string(JSON manifest SET "${manifest}" examples "${examples}")
string(JSON manifest SET "${manifest}" limitations
  "[\"Native terminal acceptance is a separate gate; installed consumer fixtures are headless.\",\"Static SDK requires a matching compiler, architecture, standard library and CRT.\",\"Linux dynamic libraries/libc must match the recorded tuple; no universal portability claim.\",\"Themes and market data are examples; executable defaults are compiled in.\",\"Payload hashes detect accidental corruption; manifest.json is not a signed trust assertion.\"]")
string(JSON manifest SET "${manifest}" licenses
  "[\"licenses/LICENSE.txt\",\"licenses/LICENSE.md\",\"licenses/Unicode-LICENSE.txt\",\"licenses/textual-LICENSE.txt\",\"licenses/lyra-LICENSE.txt\",\"licenses/monocypher-LICENCE.md\"]")
bundleWriteHashes("${payload}" hashes)
string(JSON manifest SET "${manifest}" files "${hashes}")
file(WRITE "${payload}/manifest.json" "${manifest}\n")

get_filename_component(outputParent "${OUTPUT_ARCHIVE}" DIRECTORY)
file(MAKE_DIRECTORY "${outputParent}")
if(CMAKE_HOST_WIN32)
  set(pendingArchive "${WORK_DIR}/candidate.zip")
  set(archiveArgs cf "${pendingArchive}" --format=zip "${bundleName}")
else()
  set(pendingArchive "${WORK_DIR}/candidate.tar.gz")
  set(archiveArgs czf "${pendingArchive}" --format=gnutar "${bundleName}")
endif()
execute_process(COMMAND "${CMAKE_COMMAND}" -E tar ${archiveArgs} WORKING_DIRECTORY "${WORK_DIR}"
  RESULT_VARIABLE result)
if(NOT result EQUAL 0)
  message(FATAL_ERROR "Cannot archive bundle; staging preserved at ${WORK_DIR}")
endif()
set(smokeArgs "-DARCHIVE=${pendingArchive}" "-DTEST_WORK_DIR=${WORK_DIR}/fresh unpack é"
  "-DCXX_COMPILER=${CMAKE_CXX_COMPILER}" "-DGENERATOR=${GENERATOR}"
  "-DFORBIDDEN_SOURCE_DIR=${source}" "-DFORBIDDEN_BUILD_DIR=${build}")
if(DEFINED PYTHON_EXECUTABLE)
  list(APPEND smokeArgs "-DPYTHON_EXECUTABLE=${PYTHON_EXECUTABLE}")
endif()
bundleRun("${CMAKE_COMMAND}" ${smokeArgs} -P "${source}/tests/bundle_smoke.cmake")
# Publication follows fresh-unpack verification, and cannot overwrite a prior result.
bundlePublishArchive("${pendingArchive}" "${OUTPUT_ARCHIVE}" archiveHash)
file(WRITE "${WORK_DIR}/bundle-receipt.txt"
  "commit=${commit}\nsource_archive_sha256=${sourceArchiveHash}\narchive=${OUTPUT_ARCHIVE}\nsha256=${archiveHash}\nconfiguration=Release\nheadless_bundle_smoke=passed\nnative_acceptance=separate_gate\n")
message(STATUS "Bundle headless checks passed: ${OUTPUT_ARCHIVE}")
message(STATUS "Archive SHA256: ${archiveHash}; build and verification evidence retained: ${WORK_DIR}")
