# Copyright (c) 2026 ttldtor.
# SPDX-License-Identifier: BSL-1.0
# Package already verified build outputs; compilation gates belong to the workflow.
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/release/package.cmake
       cmake <required -D settings> [optional -D settings] -P tools/release/package.cmake
Package already verified build outputs; compilation gates run separately.
Required -D settings (no defaults):
  SOURCE_DIR        Absolute existing checkout, without symlink, matching HEAD/tag.
  SOURCE_REVISION   Full 40-character lowercase SHA-1 commit.
  RELEASE_TAG       vMAJOR.MINOR.PATCH or vMAJOR.MINOR.PATCH-rcN (N >=1).
  PLATFORM          windows or linux (native x64 package).
  PAYLOAD_DIR       Absolute existing verified extracted bundle directory, no symlink.
  OUTPUT_DIR        Absolute existing directory containing only the verified release
                    bundle archive; separate from SOURCE_DIR and PAYLOAD_DIR.
  WORK_DIR          New absolute directory, separate from source, payload and output.
  CONFIGURATION     Release only.
  PARALLEL          Positive integer build parallelism, no explicit upper bound.
  TOOLCHAIN         Toolchain identity, matching both gate receipts.
  DEBUG_GATE_RECEIPT, RELEASE_GATE_RECEIPT  Absolute regular JSON receipt files,
                    no symlink, proving matching Debug and Release headless gates.
Linux-only required settings:
  C_COMPILER, CXX_COMPILER, GENERATOR  Explicit tools for the offline source consumer.
Optional:
  PAGES_DIR         Linux only: new absolute directory for Pages HTML, separate
                    from source/payload/output/work; omitted means no Pages staging.
  HELP=OFF          ON prints usage and returns before validation, includes or writes.
Requires CMake >=3.24, Git and the package-check/offline-consumer toolchain.
Effects: validates revision/tag/receipts and bundle provenance, stages release
assets and checks, runs offline consumers, writes release manifests and checksums.
Preserves work on failure. Does not push tags, publish releases or deploy Pages.
Exit 0 on success/help; nonzero on invalid inputs or failed verification.
Example: cmake -DHELP=ON -P tools/release/package.cmake
]=])
  return()
endif()
include("${CMAKE_CURRENT_LIST_DIR}/../package/common.cmake")

# Resolve existing ancestors to detect symlink escapes without creating new paths.
function(releaseResolvePath input output)
  cmake_path(NORMAL_PATH input OUTPUT_VARIABLE path)
  set(suffix "")
  while(NOT EXISTS "${path}")
    get_filename_component(name "${path}" NAME)
    get_filename_component(parent "${path}" DIRECTORY)
    if(parent STREQUAL path)
      message(FATAL_ERROR "Cannot resolve path: ${input}")
    endif()
    set(suffix "/${name}${suffix}")
    set(path "${parent}")
  endwhile()
  file(REAL_PATH "${path}" resolved)
  set(${output} "${resolved}${suffix}" PARENT_SCOPE)
endfunction()

function(releasePathIsInside parent child output)
  releaseResolvePath("${parent}" resolvedParent)
  releaseResolvePath("${child}" resolvedChild)
  if(CMAKE_HOST_WIN32)
    string(TOLOWER "${resolvedParent}" resolvedParent)
    string(TOLOWER "${resolvedChild}" resolvedChild)
  endif()
  cmake_path(IS_PREFIX resolvedParent "${resolvedChild}" NORMALIZE inside)
  set(${output} "${inside}" PARENT_SCOPE)
endfunction()

foreach(required IN ITEMS SOURCE_DIR SOURCE_REVISION RELEASE_TAG PLATFORM PAYLOAD_DIR
    OUTPUT_DIR WORK_DIR CONFIGURATION PARALLEL TOOLCHAIN DEBUG_GATE_RECEIPT RELEASE_GATE_RECEIPT)
  if(NOT DEFINED ${required} OR "${${required}}" STREQUAL "")
    message(FATAL_ERROR "Release packaging requires ${required}")
  endif()
endforeach()
if(NOT CONFIGURATION STREQUAL "Release" OR NOT PLATFORM MATCHES "^(windows|linux)$")
  message(FATAL_ERROR "Release packaging requires CONFIGURATION=Release and windows/linux PLATFORM")
endif()
if(NOT PARALLEL MATCHES "^[1-9][0-9]*$")
  message(FATAL_ERROR "PARALLEL must be a positive integer")
endif()
if(NOT RELEASE_TAG MATCHES "^v(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(-rc[1-9][0-9]*)?$")
  message(FATAL_ERROR "Unsupported release tag")
endif()
string(LENGTH "${SOURCE_REVISION}" revisionLength)
if(NOT revisionLength EQUAL 40 OR NOT SOURCE_REVISION MATCHES "^[0-9a-f]+$")
  message(FATAL_ERROR "SOURCE_REVISION must be a full lowercase SHA-1 commit")
endif()
foreach(configuration IN ITEMS Debug Release)
  string(TOUPPER "${configuration}" upperConfiguration)
  set(receiptPath "${${upperConfiguration}_GATE_RECEIPT}")
  if(NOT IS_ABSOLUTE "${receiptPath}" OR NOT EXISTS "${receiptPath}" OR
      IS_SYMLINK "${receiptPath}" OR IS_DIRECTORY "${receiptPath}")
    message(FATAL_ERROR "${configuration} gate receipt must be an absolute regular file")
  endif()
  file(READ "${receiptPath}" gateReceipt)
  foreach(field IN ITEMS schema_version tag commit platform configuration toolchain headless)
    string(JSON actual GET "${gateReceipt}" "${field}")
    if(field STREQUAL "schema_version")
      set(expected 1)
    elseif(field STREQUAL "tag")
      set(expected "${RELEASE_TAG}")
    elseif(field STREQUAL "commit")
      set(expected "${SOURCE_REVISION}")
    elseif(field STREQUAL "platform")
      set(expected "${PLATFORM}")
    elseif(field STREQUAL "configuration")
      set(expected "${configuration}")
    elseif(field STREQUAL "toolchain")
      set(expected "${TOOLCHAIN}")
    else()
      set(expected passed)
    endif()
    if(NOT actual STREQUAL expected)
      message(FATAL_ERROR "${configuration} gate receipt ${field} differs from requested release")
    endif()
  endforeach()
endforeach()
foreach(directory IN ITEMS SOURCE_DIR PAYLOAD_DIR OUTPUT_DIR)
  if(NOT IS_ABSOLUTE "${${directory}}" OR NOT IS_DIRECTORY "${${directory}}" OR
      "${${directory}}" MATCHES ";" OR IS_SYMLINK "${${directory}}")
    message(FATAL_ERROR "${directory} must be an absolute existing directory without symlinks")
  endif()
  file(REAL_PATH "${${directory}}" ${directory})
endforeach()
bundleRequireNewPath(WORK_DIR)
foreach(directory IN ITEMS SOURCE_DIR PAYLOAD_DIR OUTPUT_DIR)
  releasePathIsInside("${${directory}}" "${WORK_DIR}" inside)
  releasePathIsInside("${WORK_DIR}" "${${directory}}" contains)
  if(inside OR contains)
    message(FATAL_ERROR "WORK_DIR must be separate from ${directory}")
  endif()
endforeach()
releasePathIsInside("${SOURCE_DIR}" "${OUTPUT_DIR}" outputInsideSource)
if(outputInsideSource)
  message(FATAL_ERROR "OUTPUT_DIR must be outside SOURCE_DIR")
endif()
releasePathIsInside("${PAYLOAD_DIR}" "${OUTPUT_DIR}" outputInsidePayload)
releasePathIsInside("${OUTPUT_DIR}" "${PAYLOAD_DIR}" outputContainsPayload)
if(outputInsidePayload OR outputContainsPayload)
  message(FATAL_ERROR "OUTPUT_DIR must be separate from PAYLOAD_DIR")
endif()
if(DEFINED PAGES_DIR AND NOT PAGES_DIR STREQUAL "")
  if(NOT PLATFORM STREQUAL "linux")
    message(FATAL_ERROR "PAGES_DIR is supported only for Linux packaging")
  endif()
  bundleRequireNewPath(PAGES_DIR)
  foreach(directory IN ITEMS SOURCE_DIR PAYLOAD_DIR OUTPUT_DIR WORK_DIR)
    releasePathIsInside("${${directory}}" "${PAGES_DIR}" inside)
    releasePathIsInside("${PAGES_DIR}" "${${directory}}" contains)
    if(inside OR contains)
      message(FATAL_ERROR "PAGES_DIR must be separate from ${directory}")
    endif()
  endforeach()
endif()
if(PLATFORM STREQUAL "linux")
  foreach(required IN ITEMS C_COMPILER CXX_COMPILER GENERATOR)
    if(NOT DEFINED ${required} OR "${${required}}" STREQUAL "")
      message(FATAL_ERROR "Offline source consumer requires explicit ${required}")
    endif()
  endforeach()
  set(extension .tar.gz)
else()
  set(extension .zip)
endif()
set(bundleName "portals-${RELEASE_TAG}-${PLATFORM}-x64-release${extension}")
set(bundleArchive "${OUTPUT_DIR}/${bundleName}")
file(GLOB outputEntries RELATIVE "${OUTPUT_DIR}" "${OUTPUT_DIR}/*")
if(NOT outputEntries STREQUAL bundleName OR IS_SYMLINK "${bundleArchive}" OR IS_DIRECTORY "${bundleArchive}")
  message(FATAL_ERROR "OUTPUT_DIR must initially contain only the verified bundle archive")
endif()

find_program(GIT_EXECUTABLE NAMES git REQUIRED)
foreach(revision IN ITEMS HEAD "refs/tags/${RELEASE_TAG}^{commit}")
  execute_process(COMMAND "${GIT_EXECUTABLE}" -C "${SOURCE_DIR}" rev-parse --verify
    --end-of-options "${revision}" RESULT_VARIABLE result OUTPUT_VARIABLE commit
    OUTPUT_STRIP_TRAILING_WHITESPACE)
  if(NOT result EQUAL 0 OR NOT commit STREQUAL SOURCE_REVISION)
    message(FATAL_ERROR "Checkout/tag differs from SOURCE_REVISION")
  endif()
endforeach()
bundleVerifyHashes("${PAYLOAD_DIR}")
file(READ "${PAYLOAD_DIR}/manifest.json" toolchain)
foreach(field IN ITEMS commit configuration platform architecture linkStatus)
  string(JSON actual GET "${toolchain}" "${field}")
  if(field STREQUAL "commit")
    set(expected "${SOURCE_REVISION}")
  elseif(field STREQUAL "configuration")
    set(expected Release)
  elseif(field STREQUAL "platform")
    set(expected "${PLATFORM}")
  elseif(field STREQUAL "architecture")
    set(expected x64)
  else()
    set(expected passed)
  endif()
  if(NOT actual STREQUAL expected)
    message(FATAL_ERROR "Bundle manifest ${field} differs from requested release")
  endif()
endforeach()
get_filename_component(bundleWork "${PAYLOAD_DIR}" DIRECTORY)
file(READ "${bundleWork}/bundle-receipt.txt" receipt)
file(SHA256 "${bundleArchive}" bundleHash)
foreach(line IN ITEMS "commit=${SOURCE_REVISION}" "sha256=${bundleHash}"
    "configuration=Release" "headless_bundle_smoke=passed")
  string(FIND "\n${receipt}" "\n${line}\n" position)
  if(position EQUAL -1)
    message(FATAL_ERROR "Bundle receipt missing verified ${line}")
  endif()
endforeach()

file(MAKE_DIRECTORY "${WORK_DIR}/bundle-unpack")
file(ARCHIVE_EXTRACT INPUT "${bundleArchive}" DESTINATION "${WORK_DIR}/bundle-unpack")
set(unpacked "${WORK_DIR}/bundle-unpack/portals-mvp-${PLATFORM}-x64-release")
bundleVerifyHashes("${unpacked}")
file(READ "${unpacked}/manifest.json" archiveManifest)
if(NOT archiveManifest STREQUAL toolchain)
  message(FATAL_ERROR "Bundle archive and PAYLOAD_DIR manifests differ")
endif()

set(artifactNames "${bundleName}")
if(PLATFORM STREQUAL "linux")
  set(sourcePrefix "portals-${RELEASE_TAG}")
  foreach(format IN ITEMS zip tar.gz)
    set(archive "${OUTPUT_DIR}/${sourcePrefix}-source.${format}")
    bundleRun("${GIT_EXECUTABLE}" -C "${SOURCE_DIR}" archive "--format=${format}"
      "--prefix=${sourcePrefix}/" "--output=${archive}" "${SOURCE_REVISION}")
    list(APPEND artifactNames "${sourcePrefix}-source.${format}")
  endforeach()
  file(MAKE_DIRECTORY "${WORK_DIR}/source-unpack")
  file(ARCHIVE_EXTRACT INPUT "${OUTPUT_DIR}/${sourcePrefix}-source.tar.gz"
    DESTINATION "${WORK_DIR}/source-unpack")
  set(snapshot "${WORK_DIR}/source-unpack/${sourcePrefix}")
  if(EXISTS "${snapshot}/.work" OR EXISTS "${snapshot}/.git")
    message(FATAL_ERROR "Source archive contains private/Git state")
  endif()
  set(consumerBuild "${WORK_DIR}/source-consumer-build")
  bundleRun("${CMAKE_COMMAND}" -S "${snapshot}/examples/consumer" -B "${consumerBuild}"
    -G "${GENERATOR}" "-DCMAKE_BUILD_TYPE=${CONFIGURATION}"
    "-DCMAKE_C_COMPILER=${C_COMPILER}" "-DCMAKE_CXX_COMPILER=${CXX_COMPILER}"
    -DPORTALS_BUILD_TESTS=OFF -DPORTALS_BUILD_EXAMPLES=OFF -DPORTALS_BUILD_TOOLS=OFF
    -DPORTALS_BUILD_DOCS=OFF -DPORTALS_BUILD_FUZZERS=OFF -DFETCHCONTENT_FULLY_DISCONNECTED=ON)
  bundleRun("${CMAKE_COMMAND}" --build "${consumerBuild}" --config "${CONFIGURATION}"
    --parallel "${PARALLEL}")
  set(consumer "${consumerBuild}/portals_consumer")
  if(NOT EXISTS "${consumer}")
    set(consumer "${consumerBuild}/${CONFIGURATION}/portals_consumer")
  endif()
  bundleRun("${consumer}")

  file(MAKE_DIRECTORY "${WORK_DIR}/docs")
  file(COPY "${PAYLOAD_DIR}/docs/html" DESTINATION "${WORK_DIR}/docs")
  file(WRITE "${WORK_DIR}/docs/html/.nojekyll" "")
  # Documentation file times are retained; byte reproducibility is not guaranteed.
  set(docsName "portals-${RELEASE_TAG}-docs.zip")
  execute_process(COMMAND "${CMAKE_COMMAND}" -E tar cf "${OUTPUT_DIR}/${docsName}"
    --format=zip html WORKING_DIRECTORY "${WORK_DIR}/docs" RESULT_VARIABLE result)
  if(NOT result EQUAL 0)
    message(FATAL_ERROR "Cannot archive HTML documentation")
  endif()
  list(APPEND artifactNames "${docsName}")
  if(DEFINED PAGES_DIR AND NOT PAGES_DIR STREQUAL "")
    file(MAKE_DIRECTORY "${PAGES_DIR}")
    file(COPY "${WORK_DIR}/docs/html/" DESTINATION "${PAGES_DIR}")
  endif()
endif()

set(manifest "{\"schema_version\":1}")
foreach(field IN ITEMS tag commit platform configuration architecture)
  if(field STREQUAL "tag")
    set(value "${RELEASE_TAG}")
  elseif(field STREQUAL "commit")
    set(value "${SOURCE_REVISION}")
  elseif(field STREQUAL "platform")
    set(value "${PLATFORM}")
  elseif(field STREQUAL "configuration")
    set(value "${CONFIGURATION}")
  else()
    set(value x64)
  endif()
  bundleJsonQuote(quoted "${value}")
  string(JSON manifest SET "${manifest}" "${field}" "${quoted}")
endforeach()
set(artifacts "[]")
list(SORT artifactNames)
set(index 0)
foreach(name IN LISTS artifactNames)
  file(SHA256 "${OUTPUT_DIR}/${name}" hash)
  file(SIZE "${OUTPUT_DIR}/${name}" size)
  bundleJsonQuote(quotedName "${name}")
  string(JSON artifacts SET "${artifacts}" ${index}
    "{\"name\":${quotedName},\"sha256\":\"${hash}\",\"size\":${size}}")
  math(EXPR index "${index} + 1")
endforeach()
string(JSON manifest SET "${manifest}" toolchain "${toolchain}")
string(JSON manifest SET "${manifest}" artifacts "${artifacts}")
# These two gates are explicit workflow attestations, not tests performed here.
string(JSON manifest SET "${manifest}" gates
  "{\"debug_headless\":\"passed\",\"release_headless\":\"passed\",\"bundle_smoke\":\"passed\",\"html_links\":\"passed\",\"native_terminal_acceptance\":\"separate gate\"}")
file(WRITE "${OUTPUT_DIR}/release-manifest-${PLATFORM}.json" "${manifest}\n")
message(STATUS "Release assets packaged for ${RELEASE_TAG} (${SOURCE_REVISION})")
