# -*- coding: utf-8; mode: tcl; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:fenc=utf-8:ft=tcl:et:sw=4:ts=4:sts=4

PortSystem                  1.0
PortGroup                   compilers 1.0
PortGroup                   legacysupport 1.1

name                        R
# Remember to set revision to 0 when bumping version
# And also to update Rversion in R PortGroup
version                     4.5.2
revision                    0

set branch                  [join [lrange [split ${version} .] 0 1] .]
categories                  math science
maintainers                 {me.com:kjell.konis @kjellpk} \
                            {i0ntempest @i0ntempest} \
                            {@barracuda156 gmail.com:vital.had} \
                            openmaintainer
license                     {GPL-2 GPL-3}

description \
    R is GNU S - an interpreted language for statistical computing

long_description \
    R is a language and environment for statistical computing and graphics. \
    R provides a wide variety of statistical (linear and nonlinear modeling, \
    classical statistical tests, time-series analysis, classification, \
    clustering, ...) and graphical techniques, and is highly extensible.

homepage                    https://www.r-project.org

master_sites                https://cran.rstudio.com/src/base/R-4/ \
                            https://cran.r-project.org/src/base/R-4/

checksums                   rmd160  f604068b0aad03465ea114b198b9696d3743ef0a \
                            sha256  0d71ff7106ec69cd7c67e1e95ed1a3cee355880931f2eb78c530014a9e379f20 \
                            size    40546249

# Avoid Apple clangs:
compiler.blacklist-append   {clang}
# Blacklist macports-clang-20+. See discussion: https://trac.macports.org/ticket/67144
# for rationale. The decision when to migrate to a new compiler
# is then in the hands of the R maintainers and will not change
# from the current defaults when these get bumped centrally.
# NOTE : Keep this setting in sync with the one in the R port.
compiler.blacklist-append   {macports-clang-2[0-9]}
# Similarly, for gcc select the gcc14 variant of the compilers PG.
# This setting should also be kept in sync with that in the R Port.
# Updates should be coordinated with the R maintainers.
compiler.blacklist-append   {macports-gcc-1[5-9]}
# NOTE: upon the update to gcc14, please update the blacklist accordingly,
# like it is done for clangs. We would prefer using the same version of gcc and gfortran.
default_variants-append     +gcc14

# When switching to gcc14, make sure to add this flag when gcc is used
# as the primary compiler: -Wno-error=incompatible-pointer-types
# devQuartz.c:3049:35: error: passing argument 2 of 'CGContextSetFont'
# from incompatible pointer type [-Wincompatible-pointer-types]

# R bakes in the compiler, so if it is built with ccache,
# then it will require ccache to build R packages.
# Disable it to avoid an unnecessary dependency.
configure.ccache            no

compilers.choose            fc f77
compilers.setup             require_fortran
compiler.cxx_standard       2014

# https://trac.macports.org/ticket/69849
# https://bugs.r-project.org/show_bug.cgi?id=18713
if {${configure.build_arch} in [list i386 ppc]} {
    patchfiles-append       patch-fix-memsize.diff
}

# https://trac.macports.org/ticket/67298
# https://bugs.r-project.org/show_bug.cgi?id=18520
# See related: https://skia.googlesource.com/skia/+/3490263287e9432119c501884e45840de4d986bc
if {${os.platform} eq "darwin" && ${os.major} < 11} {
    patchfiles-append       patch-fix-10.6.diff
}

# We wanna ensure the same compiler is used for R itself and R packages.
# See R PortGroup.
if {[string match macports-clang-* ${configure.compiler}]} {
    set clang_v [
        string range ${configure.compiler} [
            string length macports-clang-
        ] end
    ]
    depends_build-append    port:clang-${clang_v}
    depends_run-append      port:clang-${clang_v}
} elseif {[string match macports-gcc-* ${configure.compiler}]} {
    set gcc_v [
        string range ${configure.compiler} [
            string length macports-gcc-
        ] end
    ]
    depends_build-append    port:gcc${gcc_v}
    depends_run-append      port:gcc${gcc_v}
}

depends_build-append        path:bin/pkg-config:pkgconfig

depends_lib-append          port:bzip2 \
                            port:curl \
                            port:gnutar \
                            port:gzip \
                            path:lib/pkgconfig/icu-uc.pc:icu \
                            port:ld64 \
                            port:less \
                            port:libiconv \
                            path:include/turbojpeg.h:libjpeg-turbo \
                            port:libpng \
                            port:pcre \
                            port:pcre2 \
                            port:readline \
                            port:texinfo \
                            port:tiff \
                            port:unzip \
                            port:xz \
                            port:zip \
                            port:zlib

legacysupport.newest_darwin_requires_legacy 10

# avoid finding ${prefix}/bin/xdg-open first
configure.env-append        R_PDFVIEWER=/usr/bin/open \
                            R_BROWSER=/usr/bin/open

# See https://trac.macports.org/ticket/66095, remove after upstream fix
platform darwin 22 {
     macosx_deployment_target 12.0
}

universal_variant           no

set resources               ${frameworks_dir}/R.framework/Versions/${branch}/Resources

post-patch {
    reinplace "s|R_HOME|\"${resources}\"|" "${worksrcpath}/src/unix/Rscript.c"

    # Check to see if this is fixed post 3.3.0
    reinplace "s|<libintl.h>|\"libintl.h\"|" "${worksrcpath}/src/include/Defn.h"

    if {${os.platform} eq "darwin" && ${os.major} < 17} {
        reinplace "s|/var/db/timezone/zoneinfo|/usr/share/zoneinfo|g" \
            "${worksrcpath}/src/extra/tzone/localtime.c" \
            "${worksrcpath}/src/library/base/man/timezones.Rd" \
            "${worksrcpath}/src/library/base/R/datetime.R"
    }
}

# Note: if Aqua support is desired, gcc may not be used for the C compiler
# on some OS X versions due to lack of support for Apple blocks extension:
# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78352
# However, it works fine on < 10.7. See also: https://trac.macports.org/ticket/66453

configure.pre_args          --prefix=${frameworks_dir}

configure.args              --disable-java \
                            --disable-openmp \
                            --enable-BLAS-shlib \
                            --enable-R-framework \
                            --enable-R-shlib \
                            --enable-memory-profiling \
                            --with-included-gettext \
                            --without-aqua \
                            --without-cairo \
                            --without-recommended-packages \
                            --without-tcltk \
                            --without-x

# disable tex/latex the hard way as there's no configure args for these
configure.env-append        ac_cv_path_TEX= \
                            ac_cv_path_PDFTEX= \
                            ac_cv_path_PDFLATEX=

platform darwin 13 {
    configure.cflags-append -flax-vector-conversions
}

variant accelerate conflicts atlas builtin_lapack openblas description {build using the BLAS and Lapack in Apple's Accelerate framework} {
    if { ([vercmp ${xcodeversion} >= 14.3] || \
        [vercmp ${xcodecltversion} >= 14.3]) && \
        (${os.platform} eq "darwin" && ${os.version} >=  22.3) } {
            configure.args-append --with-newAccelerate=lapack
    } else {
        configure.args-append   --with-blas="-framework Accelerate" --with-lapack
    }
}

variant atlas conflicts accelerate builtin_lapack openblas description {build using the BLAS in the atlas port} {
    depends_lib-append      port:atlas
    configure.args-append   --with-blas="-L${prefix}/lib -lptf77blas -latlas"
    #See A.3.2 in R Installation and Administration for why atlas LAPACK not used
}

variant builtin_lapack conflicts accelerate atlas openblas description {build using reference BLAS and Lapack} {
    configure.args-append   --without-blas --without-lapack
}

variant openblas conflicts builtin_lapack accelerate atlas description {build using the BLAS and Lapack in the OpenBLAS port} {
    depends_lib-append      path:lib/libopenblas.dylib:OpenBLAS
    configure.args-delete   --enable-BLAS-shlib
    configure.args-append   --with-blas="-L${prefix}/lib -lopenblas" --with-lapack
}

variant openmp description {enable parallelism support using OpenMP} {
    compiler.openmp_version 4.5
    compiler.blacklist-append   {macports-clang-[0-9].*}
    configure.args-replace  --disable-openmp --enable-openmp
    notes-append "
        Some R packages using OpenMP may require additional flags\
        in the Makevar file (e.g. data.table) to build with OpenMP support.\
        Please consult package documentation."
}

variant cairo description {use cairo and pango} {
    depends_lib-append      path:lib/pkgconfig/cairo.pc:cairo \
                            path:lib/pkgconfig/pango.pc:pango \
                            path:lib/pkgconfig/glib-2.0.pc:glib2 \
                            port:freetype \
                            port:fontconfig \
                            port:gettext-runtime
    configure.args-replace  --without-cairo \
                            --with-cairo
}

variant debug description {build with debug symbols} {
    configure.optflags-append -g
}

variant latex description {build with LaTeX support and docs in PDF} {
    depends_build-append    port:texlive-basic \
                            port:texlive-latex \
                            port:texlive-latex-recommended
    configure.env-delete    ac_cv_path_TEX= \
                            ac_cv_path_PDFTEX= \
                            ac_cv_path_PDFLATEX=
}

variant tcltk description {enable use of tcltk} {
    depends_lib-append      port:tcl
    if {[variant_isset quartz]} {
        depends_lib-append      port:tk-quartz
        configure.args-append   --with-tk-config=${prefix}/lib/tk-quartz/tkConfig.sh
    } else {
        depends_lib-append      port:tk-x11
        configure.args-append   --with-tk-config=${prefix}/lib/tk-x11/tkConfig.sh
    }
    configure.args-delete   --without-tcltk
    configure.args-append   --with-tcltk \
                            --with-tcl-config=${prefix}/lib/tclConfig.sh
}

variant tests description {include tests of R installation} {
    destroot.target-append install-tests
}

variant x11 conflicts quartz {
    depends_lib-append      port:xorg-libice \
                            port:xorg-libsm \
                            port:xorg-libX11 \
                            port:xorg-libXmu \
                            port:xorg-libXt
    configure.args-delete   --without-x
    configure.args-append   --with-x \
                            --x-include=${prefix}/include/X11 \
                            --x-lib=${prefix}/lib
}

variant aqua description {Enable native macOS graphics support, needed by R.app and quartz variant} {
    configure.args-replace  --without-aqua \
                            --with-aqua
}

variant quartz requires aqua conflicts x11 {
    notes-append "
        Note that R with quartz variant will not work with R.app because\
        of conflicts over the macOS menu."
}

variant java description {enable Java} {
    PortGroup java 1.0

    configure.args-replace  --disable-java \
                            --enable-java
}

default_variants-append     +aqua +cairo +openmp +tcltk

if {![variant_isset quartz]} {
    default_variants-append +x11
}

if {[variant_isset cairo] && [variant_isset x11]} {
    require_active_variants path:lib/pkgconfig/cairo.pc:cairo x11
    require_active_variants path:lib/pkgconfig/pango.pc:pango x11
}

if {[variant_isset cairo] && [variant_isset quartz]} {
    require_active_variants path:lib/pkgconfig/cairo.pc:cairo quartz
    require_active_variants path:lib/pkgconfig/pango.pc:pango quartz
}

if {![variant_isset accelerate] && ![variant_isset atlas] && ![variant_isset openblas] && ![variant_isset builtin_lapack]} {
    default_variants-append +builtin_lapack
}

test.run                    yes
test.target                 check

destroot.destdir prefix=${destroot}${frameworks_dir}

post-destroot {
    copy ${destroot}${frameworks_dir}/R.framework/Resources/lib/pkgconfig/libR.pc ${destroot}${prefix}/lib/pkgconfig/libR.pc

    foreach v { "rhome" "rincludedir" } {
        reinplace "s|${v}=${destroot}|${v}=|" "${destroot}${prefix}/lib/pkgconfig/libR.pc"
    }

    foreach dir { "R_HOME_DIR" "R_SHARE_DIR" "R_INCLUDE_DIR" "R_DOC_DIR" } {
        reinplace "s|${dir}=${destroot}|${dir}=|" "${destroot}${resources}/bin/R"
    }

    reinplace "s|-F${destroot}|-F|" "${destroot}${resources}/etc/Makeconf"

    foreach dylib [ exec find ${destroot}${frameworks_dir}/R.framework -name "\*.dylib" ] {
        regsub ":$" ${dylib} "" destroot_dylib_path
        regsub ${destroot} ${destroot_dylib_path} "" dylib_path
        system "install_name_tool -id ${dylib_path} ${destroot_dylib_path}"
        system "install_name_tool -change ${destroot}${resources}/lib/libR.dylib ${resources}/lib/libR.dylib \
            ${destroot_dylib_path}"
        system "install_name_tool -change ${destroot}${resources}/lib/libRblas.dylib ${resources}/lib/libRblas.dylib \
            ${destroot_dylib_path}"
        system "install_name_tool -change ${destroot}${resources}/lib/libRlapack.dylib ${resources}/lib/libRlapack.dylib \
            ${destroot_dylib_path}"
    }

    foreach so [ exec find ${destroot}${frameworks_dir}/R.framework -name "\*.so" ] {
        regsub ":$" ${so} "" destroot_so_path
        regsub ${destroot} ${destroot_so_path} "" so_path
        system "install_name_tool -id ${so_path} ${destroot_so_path}"
        system "install_name_tool -change ${destroot}${resources}/lib/libR.dylib ${resources}/lib/libR.dylib \
            ${destroot_so_path}"
        system "install_name_tool -change ${destroot}${resources}/lib/libRblas.dylib ${resources}/lib/libRblas.dylib \
            ${destroot_so_path}"
        system "install_name_tool -change ${destroot}${resources}/lib/libRlapack.dylib ${resources}/lib/libRlapack.dylib \
            ${destroot_so_path}"
    }

    system "install_name_tool -change ${destroot}${resources}/lib/libR.dylib ${resources}/lib/libR.dylib \
        ${destroot}${resources}/bin/exec/R"
    system "install_name_tool -change ${destroot}${resources}/lib/libRblas.dylib ${resources}/lib/libRblas.dylib \
        ${destroot}${resources}/bin/exec/R"

    platform darwin {
        # LegacySupport magic does not work automatically. Re-implement it by hand:
        set rexec ${resources}/bin/exec/R

        if {${os.major} < 11} {
            legacysupport::relink_libSystem ${destroot}${rexec}
        }

        if {${configure.cxx_stdlib} ne "libc++"} {
            # We can’t do it in a sane way, since R build system in its wisdom assumes
            # that R and R-orig are archs, and then package installation gets broken.
            set rexec_orig ${resources}/bin/exec_orig/R

            xinstall -d ${destroot}${resources}/bin/exec_orig

            move ${destroot}${rexec} ${destroot}${rexec_orig}

            set  wrapper    [open "${destroot}${rexec}" w 0755]
            puts ${wrapper} "#!/bin/bash"
            puts ${wrapper} ""
            puts ${wrapper} {if [ -n "$DYLD_LIBRARY_PATH" ]; then}
            puts ${wrapper} "   DYLD_LIBRARY_PATH=${prefix}/lib/libgcc:\${DYLD_LIBRARY_PATH}"
            puts ${wrapper} {else}
            puts ${wrapper} "   DYLD_LIBRARY_PATH=${prefix}/lib/libgcc"
            puts ${wrapper} {fi}
            puts ${wrapper} {export DYLD_LIBRARY_PATH}
            puts ${wrapper} ""
            puts ${wrapper} "exec ${rexec_orig} \"\$@\""
            close $wrapper
        }
    }

    ln -s ${resources}/bin/R ${destroot}${prefix}/bin/R
    ln -s ${resources}/bin/Rscript ${destroot}${prefix}/bin/Rscript
    foreach f [glob -type f -directory ${destroot}${resources}/share/man/man1 *] {
        set fname [file tail ${f}]
        ln -s ${resources}/share/man/man1/${fname} ${destroot}${prefix}/share/man/man1/${fname}
    }
}

livecheck.type      regex
livecheck.url       [lindex ${master_sites} 0]
livecheck.regex     >${name}-(\[0-9.\]+)${extract.suffix}<
