# Copyright (c) 2026 ttldtor.
# SPDX-License-Identifier: BSL-1.0
# Internal include; no standalone CLI. Functions take explicit arguments.
# Function contracts and callers: docs/developer-tools-release.md.
# Shared, build-independent validation for bundle creation and fresh unpack tests.
cmake_minimum_required(VERSION 3.24)

function(bundleStageConsumer source destination)
  file(COPY "${source}/tests/package_consumer/" DESTINATION "${destination}")
  # Keep complete guide sources beside the consumer targets without a second file list to maintain.
  file(COPY "${source}/docs/examples/" DESTINATION "${destination}/docs/examples"
    PATTERN "CMakeLists.txt" EXCLUDE)
  # Browser development dependencies are not native consumer sources.
  file(COPY "${source}/examples" DESTINATION "${destination}" PATTERN "node_modules" EXCLUDE)
  file(COPY "${source}/tests/examples" "${source}/tests/support" DESTINATION "${destination}/tests")
  if(CMAKE_HOST_WIN32)
    file(COPY "${source}/tests/support/no_dialogs.cpp" DESTINATION "${destination}")
  endif()
endfunction()

function(bundlePublishArchive pendingArchive outputArchive outputHash)
  # Copy onto the output filesystem before the no-overwrite publication step.
  string(RANDOM LENGTH 32 ALPHABET 0123456789abcdef publicationId)
  set(publicationCandidate "${outputArchive}.candidate-${publicationId}")
  bundleRequireNewPath(publicationCandidate)
  file(COPY_FILE "${pendingArchive}" "${publicationCandidate}" RESULT copyResult)
  if(NOT copyResult STREQUAL "0")
    message(FATAL_ERROR "Cannot copy verified archive: ${copyResult}")
  endif()
  file(SHA256 "${pendingArchive}" verifiedHash)
  file(SHA256 "${publicationCandidate}" copiedHash)
  if(NOT copiedHash STREQUAL verifiedHash)
    message(FATAL_ERROR "Copied archive bytes differ; candidates preserved")
  endif()
  file(RENAME "${publicationCandidate}" "${outputArchive}" NO_REPLACE RESULT renameResult)
  if(NOT renameResult STREQUAL "0")
    message(FATAL_ERROR "Cannot publish bundle: ${renameResult}")
  endif()
  file(SHA256 "${outputArchive}" archiveHash)
  if(NOT archiveHash STREQUAL verifiedHash)
    message(FATAL_ERROR "Published archive bytes differ; candidates preserved")
  endif()
  # Older CMake on Unix leaves the original hard link after RENAME NO_REPLACE.
  # Remove only this call's exact candidate after successful, verified publication.
  file(REMOVE "${publicationCandidate}")
  if(EXISTS "${publicationCandidate}" OR IS_SYMLINK "${publicationCandidate}")
    message(FATAL_ERROR "Cannot remove published archive candidate: ${publicationCandidate}")
  endif()
  set(${outputHash} "${archiveHash}" PARENT_SCOPE)
endfunction()

function(bundleRun)
  execute_process(COMMAND ${ARGV} RESULT_VARIABLE result)
  if(NOT result EQUAL 0)
    message(FATAL_ERROR "Bundle command failed (${result}): ${ARGV}")
  endif()
endfunction()

function(bundleJsonQuote output value)
  string(REPLACE "\\" "\\\\" escaped "${value}")
  string(REPLACE "\"" "\\\"" escaped "${escaped}")
  string(REPLACE "\r" "\\r" escaped "${escaped}")
  string(REPLACE "\n" "\\n" escaped "${escaped}")
  string(REPLACE "\t" "\\t" escaped "${escaped}")
  set(${output} "\"${escaped}\"" PARENT_SCOPE)
endfunction()

function(bundleRequireNewPath variable)
  if(NOT DEFINED ${variable} OR "${${variable}}" STREQUAL "")
    message(FATAL_ERROR "Bundle requires ${variable}")
  endif()
  if(NOT IS_ABSOLUTE "${${variable}}")
    message(FATAL_ERROR "${variable} must be absolute: ${${variable}}")
  endif()
  if("${${variable}}" MATCHES ";")
    message(FATAL_ERROR "${variable} cannot contain a CMake list separator")
  endif()
  cmake_path(NORMAL_PATH ${variable} OUTPUT_VARIABLE normalized)
  if(EXISTS "${normalized}" OR IS_SYMLINK "${normalized}")
    message(FATAL_ERROR "${variable} already exists; preserve it and choose a new path: ${normalized}")
  endif()
  set(${variable} "${normalized}" PARENT_SCOPE)
endfunction()

function(bundleValidateRelativePath path)
  if("${path}" STREQUAL "" OR IS_ABSOLUTE "${path}" OR
      "${path}" MATCHES "(^|[/\\\\])\\.\\.([/\\\\]|$)" OR
      "${path}" MATCHES "[;\\\\:\r\n]")
    message(FATAL_ERROR "Unsafe bundle-relative path: ${path}")
  endif()
endfunction()


function(bundlePathIsInside parent child output)
  file(REAL_PATH "${parent}" normalizedParent)
  file(REAL_PATH "${child}" normalizedChild)
  if(CMAKE_HOST_WIN32)
    string(TOLOWER "${normalizedParent}" normalizedParent)
    string(TOLOWER "${normalizedChild}" normalizedChild)
  endif()
  cmake_path(IS_PREFIX normalizedParent "${normalizedChild}" NORMALIZE inside)
  set(${output} "${inside}" PARENT_SCOPE)
endfunction()

function(bundleRejectSymlinks root)
  file(GLOB_RECURSE entries LIST_DIRECTORIES TRUE "${root}/*")
  foreach(entry IN LISTS entries)
    if(IS_SYMLINK "${entry}")
      message(FATAL_ERROR "Bundle contains an unsupported symlink: ${entry}")
    endif()
  endforeach()
endfunction()
function(bundleWriteHashes root output)
  bundleRejectSymlinks("${root}")
  file(GLOB_RECURSE files LIST_DIRECTORIES FALSE RELATIVE "${root}" "${root}/*")
  list(SORT files)
  set(entries "")
  foreach(relative IN LISTS files)
    if(relative STREQUAL "manifest.json")
      continue()
    endif()
    bundleValidateRelativePath("${relative}")
    if(IS_SYMLINK "${root}/${relative}")
      message(FATAL_ERROR "Bundle contains an unsupported symlink: ${relative}")
    endif()
    file(SHA256 "${root}/${relative}" hash)
    bundleJsonQuote(quotedPath "${relative}")
    string(APPEND entries "${separator}${quotedPath}:\"${hash}\"")
    set(separator ",\n")
  endforeach()
  set(${output} "{\n${entries}\n}" PARENT_SCOPE)
endfunction()

function(bundleVerifyHashes root)
  bundleRejectSymlinks("${root}")
  if(NOT EXISTS "${root}/manifest.json")
    message(FATAL_ERROR "Bundle manifest.json is missing")
  endif()
  file(READ "${root}/manifest.json" manifest)
  string(JSON schema ERROR_VARIABLE error GET "${manifest}" schema_version)
  if(NOT error STREQUAL "NOTFOUND" OR NOT schema EQUAL 1)
    message(FATAL_ERROR "Unsupported or invalid bundle manifest")
  endif()
  string(JSON count LENGTH "${manifest}" files)
  if(count LESS 1)
    message(FATAL_ERROR "Bundle manifest contains no payload files")
  endif()
  math(EXPR last "${count} - 1")
  set(expected "")
  foreach(index RANGE 0 ${last})
    string(JSON relative MEMBER "${manifest}" files ${index})
    bundleValidateRelativePath("${relative}")
    if(relative STREQUAL "manifest.json" OR IS_SYMLINK "${root}/${relative}" OR
        NOT EXISTS "${root}/${relative}" OR IS_DIRECTORY "${root}/${relative}")
      message(FATAL_ERROR "Missing or invalid payload file: ${relative}")
    endif()
    string(JSON expectedHash GET "${manifest}" files "${relative}")
    file(SHA256 "${root}/${relative}" actualHash)
    if(NOT expectedHash STREQUAL actualHash)
      message(FATAL_ERROR "SHA256 mismatch: ${relative}")
    endif()
    list(APPEND expected "${relative}")
  endforeach()
  file(GLOB_RECURSE actual LIST_DIRECTORIES FALSE RELATIVE "${root}" "${root}/*")
  list(REMOVE_ITEM actual manifest.json)
  list(SORT expected)
  list(SORT actual)
  if(NOT actual STREQUAL expected)
    message(FATAL_ERROR "Bundle file inventory differs from manifest.json")
  endif()
endfunction()
