# Pure cmake script to generate licence.h from LICENCE

file(READ "${LICENCE_FILE}" LICENCE_TEXT)

function(c_string_escape outvar value)
  string(REPLACE "\\" "\\\\" value "${value}")
  string(REPLACE "\"" "\\\"" value "${value}")
  set("${outvar}" "${value}" PARENT_SCOPE)
endfunction()

set(copyright_regex "PuTTY is copyright ([0-9]+-[0-9]+ [^\n]*[^\n.])\\.?\n")
string(REGEX MATCH "${copyright_regex}" COPYRIGHT_NOTICE "${LICENCE_TEXT}")
string(REGEX REPLACE "${copyright_regex}" "\\1"
  COPYRIGHT_NOTICE "${COPYRIGHT_NOTICE}")
c_string_escape(COPYRIGHT_NOTICE "${COPYRIGHT_NOTICE}")

string(REGEX REPLACE "\n$" "" LICENCE_TEXT "${LICENCE_TEXT}")
string(REPLACE "\r" "" LICENCE_TEXT "${LICENCE_TEXT}")
string(REPLACE "\n\n" "\r" LICENCE_TEXT "${LICENCE_TEXT}")
string(REPLACE "\n" " " LICENCE_TEXT "${LICENCE_TEXT}")
string(REPLACE "\r" "\n" LICENCE_TEXT "${LICENCE_TEXT}")

c_string_escape(LICENCE_TEXT "${LICENCE_TEXT}")
string(REPLACE "\n" "\" \\\n    parsep \\\n    \""
  LICENCE_TEXT "${LICENCE_TEXT}")

file(WRITE "${OUTPUT_FILE}" "\
/*
 * licence.h - macro definitions for the PuTTY licence.
 *
 * Generated by cmake/licence.cmake from ./LICENCE.
 * You should edit those files rather than editing this one.
 */

#define LICENCE_TEXT(parsep) \\
    \"${LICENCE_TEXT}\"

#define SHORT_COPYRIGHT_DETAILS \"${COPYRIGHT_NOTICE}\"
")
