#  Copyright (C) 2025 KeePassXC Team <team@keepassxc.org>
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 2 or (at your option)
#  version 3 of the License.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.

set(_installdir ${CPACK_TEMPORARY_INSTALL_DIRECTORY})
set(_sign @WITH_XC_SIGNINSTALL@)
set(_cert_thumbprint @WITH_XC_SIGNINSTALL_CERT@)
set(_timestamp_url @WITH_XC_SIGNINSTALL_TIMESTAMP_URL@)

# Setup portable zip file if building one
if(_installdir MATCHES "/ZIP/")
  file(TOUCH "${_installdir}/.portable")
  message(STATUS "Injected portable zip file.")
endif()

# Find all dll and exe files in the install directory
file(GLOB_RECURSE _sign_files
      RELATIVE "${_installdir}"
      "${_installdir}/*.dll"
      "${_installdir}/*.exe"
)

# Sign relevant binaries if requested
if(_sign AND _sign_files)
  # Find signtool in PATH or error out
  find_program(_signtool signtool.exe QUIET)
  if(NOT _signtool)
    message(FATAL_ERROR "signtool.exe not found in PATH, correct or unset WITH_XC_SIGNINSTALL")
  endif()

  # Set a default timestamp URL if none was provided
  if (NOT _timestamp_url)
    set(_timestamp_url "http://timestamp.sectigo.com")
  endif()

  # Check that a certificate thumbprint was provided or error out
  if (NOT _cert_thumbprint)
    message(STATUS "Signing using best available certificate.")
    set(_certopt /a)
  else()
    message(STATUS "Signing using certificate with thumbprint ${_cert_thumbprint}.")
    set(_certopt /sha1 ${_cert_thumbprint})
  endif()

  message(STATUS "Signing binary files with signtool, this may take a while...")
  # Use cmd /c to enable pop-up for pin entry if needed
  execute_process(
      COMMAND cmd /c ${_signtool} sign /fd SHA256 ${_certopt} /tr ${_timestamp_url} /td SHA256 ${_sign_files}
      WORKING_DIRECTORY "${_installdir}"
      RESULT_VARIABLE sign_result
      OUTPUT_VARIABLE sign_output
      ERROR_VARIABLE sign_error
      OUTPUT_STRIP_TRAILING_WHITESPACE
      ERROR_STRIP_TRAILING_WHITESPACE
      ECHO_OUTPUT_VARIABLE
  )
  if (NOT sign_result EQUAL 0)
    message(FATAL_ERROR "signtool failed: ${sign_error}")
  endif()
endif()
