# Part of the rstantools package
# Copyright (C) 2018 Trustees of Columbia University
#
# rstantools 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 3
# of the License, or (at your option) any later version.
#
# rstantools 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

#' Register functions implemented in C++
#'
#' If you set up your package using `rstan_package_skeleton()` before
#' version `1.2.1` of \pkg{rstantools} it may be necessary for you to call
#' this function yourself in order to pass `R CMD check` in \R
#' `>= 3.4`. If you used `rstan_package_skeleton()` in \pkg{rstantools} version
#' `1.2.1` or later then this has already been done automatically.
#'
#' @export
#' @param name The name of your package as a string.
#' @param path The path to the root directory for your package as a string. If
#'   not specified it is assumed that this is already the current working
#'   directory.
#' @return This function is only called for its side effect of writing the
#'   necessary `init.cpp` file to the package's `src/` directory.
#'
init_cpp <- function(name, path) {
  file <- file.path("src", "init.cpp")
  if (!missing(path))
    file <- file.path(path, file)

  writeLines(c(
    "// Generated by the rstantools package",
    "", "",
    "#include <R.h>",
    "#include <Rinternals.h>",
    "#include <R_ext/Rdynload.h>",
    "#include <R_ext/Visibility.h>",
    "#include <Rversion.h>",
    "", "",
    "static const R_CallMethodDef CallEntries[] = {",
    "  {NULL, NULL, 0}",
    "};",
    "", "",
    paste0("void attribute_visible R_init_", name, "(DllInfo *dll) {"),
    "  // next line is necessary to avoid a NOTE from R CMD check",
    "  R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);",
    "  R_useDynamicSymbols(dll, TRUE); // necessary for .onLoad() to work",
    "}"
    ),
    con = file
  )
  return(invisible(NULL))
}
