#-----------------------------------------------------------------------------
#  Copyright (C) 2025 Thomas S. Ullrich
#
#  This file is part of "xyscan".
#
#  This file may be used under the terms of the GNU General Public License.
#  This project is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License.
#
#  Author: Thomas S. Ullrich
#  Last update: Oct 31, 2025
#-----------------------------------------------------------------------------
# update_version.cmake
# Stamps @VERSION@ into license.txt (all platforms) and, when provided,
# into the macOS app bundle's Info.plist.
#
# Inputs (required unless marked optional):
#   - APP_BIN         : path to built xyscan executable
#   - LICENSE_SRC     : source template license.txt with @VERSION@
#   - LICENSE_DST     : stamped license.txt written to build tree
#   - (optional) PLIST_INBUNDLE  : <bundle>/Contents/Info.plist (macOS)
#   - (optional) PLIST_TEMPLATE  : source template Info.plist with @VERSION@ (macOS)
#-----------------------------------------------------------------------------
if(NOT DEFINED APP_BIN)
  message(FATAL_ERROR "APP_BIN not set")
endif()
if(NOT DEFINED LICENSE_SRC OR NOT DEFINED LICENSE_DST)
  message(FATAL_ERROR "LICENSE_SRC and LICENSE_DST must be set")
endif()

# 1) Query version from the executable
execute_process(
  COMMAND "${APP_BIN}" --numeric-version
  OUTPUT_VARIABLE XYSCAN_VER
  OUTPUT_STRIP_TRAILING_WHITESPACE
  RESULT_VARIABLE _ver_rc
)
if(NOT _ver_rc EQUAL 0 OR XYSCAN_VER STREQUAL "")
  message(FATAL_ERROR "Failed to read version from ${APP_BIN} --numeric-version")
endif()

# 2) Stamp license.txt
if(NOT EXISTS "${LICENSE_SRC}")
  message(FATAL_ERROR "LICENSE_SRC not found: ${LICENSE_SRC}")
endif()
file(READ "${LICENSE_SRC}" _license)
string(REPLACE "@VERSION@" "${XYSCAN_VER}" _license "${_license}")
get_filename_component(_lic_dir "${LICENSE_DST}" DIRECTORY)
file(MAKE_DIRECTORY "${_lic_dir}")
file(WRITE "${LICENSE_DST}" "${_license}")

# 3) Stamp Info.plist if mac-only vars are present
if(DEFINED PLIST_INBUNDLE AND DEFINED PLIST_TEMPLATE
   AND NOT ("${PLIST_INBUNDLE}" STREQUAL "") AND NOT ("${PLIST_TEMPLATE}" STREQUAL ""))

  if(EXISTS "${PLIST_TEMPLATE}")
    file(READ "${PLIST_TEMPLATE}" _plist)
    string(REPLACE "@VERSION@" "${XYSCAN_VER}" _plist "${_plist}")
    get_filename_component(_plist_dir "${PLIST_INBUNDLE}" DIRECTORY)
    file(MAKE_DIRECTORY "${_plist_dir}")
    file(WRITE "${PLIST_INBUNDLE}" "${_plist}")
  else()
    message(WARNING "PLIST_TEMPLATE not found: ${PLIST_TEMPLATE} (skipping plist stamping)")
  endif()
endif()

message(STATUS "xyscan version stamped: ${XYSCAN_VER}")
message(STATUS "  license.txt -> ${LICENSE_DST}")
if(DEFINED PLIST_INBUNDLE AND NOT ("${PLIST_INBUNDLE}" STREQUAL ""))
  message(STATUS "  Info.plist  -> ${PLIST_INBUNDLE}")
endif()
