####
#
# Based partly on package(s) or directions found at these URLs
#     https://www.archlinux.org/packages/community/x86_64/julia/
#     https://github.com/JuliaLang/julia/blob/master/doc/build/build.md
#     https://github.com/JuliaLang/julia/blob/master/doc/build/windows.md
#     https://github.com/JuliaLang/julia/blob/master/doc/build/distributing.md
#
# Maintainer: gym603 <gui_yuan_miao@163.com>
# Contributor: Tim Stahlhut <stahta01@gmail.com>
#
####
#
# Normal build command
#   makepkg-mingw -sLf --nocheck
#
# Added tty and msg2 start and finish messages because of makepkg log
#   lockups. They help to figure out which tee command to kill.
#
####

_make_verbose=0           # 0 or 1    (PR value is 0)
_show_log_lockup_info=0   # 0 or 1    (PR value is 0)

_realname=julia
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=1.4.1
pkgrel=1
_rc=
_sourcedir=${_realname}-${pkgver}${_rc}
pkgdesc="High-level, high-performance, dynamic programming language for technical computing (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64')
url="https://julialang.org/"
license=('MIT')
depends=("p7zip"
         "${MINGW_PACKAGE_PREFIX}-gcc-libs"
         "${MINGW_PACKAGE_PREFIX}-suitesparse"
         "${MINGW_PACKAGE_PREFIX}-lapack"
         "${MINGW_PACKAGE_PREFIX}-openblas"
         "${MINGW_PACKAGE_PREFIX}-libunwind")
makedepends=("patch"
             "make"
             "tar"
             "${MINGW_PACKAGE_PREFIX}-gcc-fortran"
             "${MINGW_PACKAGE_PREFIX}-gmp"
             "${MINGW_PACKAGE_PREFIX}-diffutils"
             "${MINGW_PACKAGE_PREFIX}-python2"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "perl")
source=(${_sourcedir}.tar.gz::https://github.com/JuliaLang/julia/releases/download/v${pkgver}/${_realname}-${pkgver}${_rc}.tar.gz
        003-1.1.1-msys2-fix-CMAKE_GENERATOR_COMMAND-and-CMAKE_C_COMPILER.patch
        004-1.1.1-msys2-fix-base-floatfuncs.jl.patch
        007-1.3.0-pkgbuild-make-install-no-build.patch
        008-1.1.1-msys2-fix-i686-gcc-dll-name.patch
        009-1.1.1-msys2-find-modname-in-julia_dl-before-default-paths.patch
        010-1.3.0-msys2-fix-install-dir.patch
        012-1.1.1-gcc-remove-USING_SJLJ_EXCEPTIONS.patch
        015-1.1.1-mingw-use-O2-instead-of-O3.patch
        016-1.3.0-msys2-Add-SRCCACHE-LIBGIT2_SRC_DIR-source-extracted-target.patch
        017-1.4.1-backport-1.4.2-Add-GCC10-to-GCC-version-mappings-35849.patch
        018-1.4.1-llvm-8.0.1-D64937-gcc10.patch
        019-1.4.1-port-nl-libgit2-v0.99.0.patch
       )
sha256sums=('71709a1e04f4f4ac54668cc32530a7d36062ee890fafbcba8dec178987fa0a0c'
            'b9a82888f79ce2786a68919b37eb52f0dd44cbac53dd49a6e95401916fa4edd2'
            '221023d4ebf2721a9b5cedbc6a3550c26c3c9897f5332a6ea4a68ec1f1510b05'
            '75187094bda0c52d90e5ae9fc3fe170f23ad745d5a1debe762d7da010b9df830'
            '71fb4b167b9dcf5d227e8ce7e05d35301f2f6ce2b353c4215e8282d5d3a8dc33'
            'f82628d0a12c1503ce3a032c6194392f257f49c03724d6788a6d7f5789e33982'
            '4a4c7b2257177ddf82cfcae1aac0e68b611d1b455f16ce8dd29a33ea9269aefb'
            '2c1db914a1a83245b91d66cdb1cddfa9f8b262f73125032041b8d7c6cbecb19a'
            '8c4b2007b91b8fb91cc29fae95fef26a28b655db0547019e0c40423f236b940c'
            '9ad3bd47d1b9f30bb42346495eca012e9be74e626d008a80882be3f5e30af91a'
            '93e32c0143ca3fb6392608e1cb8c0564a703b76d09996d29ec74f7f7e56d3936'
            '7128c1e721cf39c357096efe975e7eaf5de4d0d5bac763fb929f85309fedf742'
            'c8be2be8d62ea653439a5c18e56f8026c83f0f1127934b12d7faf60630befd45')

# Helper macros to help make tasks easier #
apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying ${_patch}"
    patch -Nbp1 -i "${srcdir}/${_patch}"
  done
}

_make_user_config () {
cat <<EOF >Make.user
USE_BINARYBUILDER = 0
USE_BINARYBUILDER_LLVM = 0
USE_BINARYBUILDER_OPENLIBM = 0
USE_BINARYBUILDER_LIBUV = 0
USE_BINARYBUILDER_PCRE = 0
USE_BINARYBUILDER_MBEDTLS = 0
USE_BINARYBUILDER_LIBSSH2 = 0
USE_BINARYBUILDER_LIBGIT2 = 0
USE_SYSTEM_SUITESPARSE = 1
USE_SYSTEM_LIBUV = 0
# USE_SYSTEM_LIBM = 1
# USE_SYSTEM_OPENLIBM = 1
USE_SYSTEM_DSFMT = 0
USE_SYSTEM_LLVM = 0
# USE_SYSTEM_PCRE = 1
USE_SYSTEM_BLAS = 1
LIBBLAS=-lopenblas
LIBBLASNAME=libopenblas
USE_SYSTEM_GMP = 0
USE_SYSTEM_ZLIB = 1
USE_SYSTEM_MBEDTLS = 1
USE_SYSTEM_LIBSSH2 = 1
# USE_SYSTEM_LIBGIT2 = 1
USE_SYSTEM_MPFR = 0
# USE_SYSTEM_UTF8PROC = 1
# USE_SYSTEM_CURL = 1
USE_SYSTEM_LIBUNWIND = 1
USE_SYSTEM_P7ZIP = 1
USE_SYSTEM_LAPACK = 1
EOF
}

prepare() {
  cd "${srcdir}/${_sourcedir}"

  rm -f deps/patches/llvm-8.0.1-D64937-gcc10.patch

  apply_patch_with_msg \
    003-1.1.1-msys2-fix-CMAKE_GENERATOR_COMMAND-and-CMAKE_C_COMPILER.patch \
    004-1.1.1-msys2-fix-base-floatfuncs.jl.patch \
    007-1.3.0-pkgbuild-make-install-no-build.patch \
    008-1.1.1-msys2-fix-i686-gcc-dll-name.patch \
    009-1.1.1-msys2-find-modname-in-julia_dl-before-default-paths.patch \
    010-1.3.0-msys2-fix-install-dir.patch \
    012-1.1.1-gcc-remove-USING_SJLJ_EXCEPTIONS.patch \
    015-1.1.1-mingw-use-O2-instead-of-O3.patch \
    016-1.3.0-msys2-Add-SRCCACHE-LIBGIT2_SRC_DIR-source-extracted-target.patch \
    017-1.4.1-backport-1.4.2-Add-GCC10-to-GCC-version-mappings-35849.patch \
    018-1.4.1-llvm-8.0.1-D64937-gcc10.patch

  [[ -d "${srcdir}/build-${MINGW_CHOST}" ]] && rm -rf "${srcdir}/build-${MINGW_CHOST}"
  msg2 "directory copy starting"
  cp -rp  "${srcdir}/${_sourcedir}/." "${srcdir}/build-${MINGW_CHOST}"
  msg2 "directory copy finished"

  cd "${srcdir}/build-${MINGW_CHOST}"
  _make_user_config; # create Make.user in current directory
  if [[ "$_show_log_lockup_info" == "1" ]]; then
    tty
    msg2 "prepare finished"
  fi
}

build() {
  ####  Errors found during current or past builds of Julia on MSys2
  # BB of LLVM does not work right; llvm-config returns empty results.
  # LB of GMP 6.1.2 does not work with make target configure.
  # SB of GMP 6.2.0 is not found by sysimg.jl
  # LB of lapack failed with error gfortran: Argument list too long
  # SB of libgit2 failed with error: could not load library libgit2
  #
  # BB means Binary Build done by Julia server
  # SB means System Build done by MSys2 package
  # LB means Local Build done by Julia make system running locally
  ####
  if [[ "$_show_log_lockup_info" == "1" ]]; then
    msg2 "build started"
  fi

  cd "${srcdir}/build-${MINGW_CHOST}"

  # Per distributing.md CPUs older than Pentium 4 are not supported.
  case "${CARCH}" in
    i686)
      export CFLAGS="-march=pentium4"
      export CXXFLAGS="-march=pentium4"
    ;;
  esac

  # option "-w" disables all warnings
  env CFLAGS="$CFLAGS -w" CXXFLAGS="$CXXFLAGS -w" \
    make VERBOSE=${_make_verbose} \
      LOCALBASE=${MINGW_PREFIX}
  if [[ "$_show_log_lockup_info" == "1" ]]; then
    tty
    msg2 "build finished"
  fi
}

check() {
  msg2 "check started"

  cd "${srcdir}/build-${MINGW_CHOST}"

  cd test
  make print-TESTS # list the tests
  env PATH="${srcdir}/build-${MINGW_CHOST}/usr/bin:$PATH" \
    ../usr/bin/julia --check-bounds=yes --startup-file=no ./runtests.jl all --skip Sockets --skip Distributed --skip LibGit2/libgit2 --skip FileWatching --skip file
  find ../stdlib \( -name \*.cov -o -name \*.mem \) -delete
  rm -r depot/compiled
  if [[ "$_show_log_lockup_info" == "1" ]]; then
    tty
    msg2 "check finished"
  fi
}

package_julia() {
  backup=("${MINGW_PREFIX:1}"/etc/julia/startup.jl)

  cd "${srcdir}/build-${MINGW_CHOST}"

  make DESTDIR="${pkgdir}" install \
    prefix=${MINGW_PREFIX}

  # Documentation is in the julia-docs package.
  rm -rf "$pkgdir${MINGW_PREFIX}/share/"{doc,julia/doc}
  # Man pages in share/man are duplicate.
  #rm -rf "$pkgdir${MINGW_PREFIX}/share/man"

  install -Dm644 LICENSE.md "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE.md"
}

package_julia-docs() {
  pkgdesc='Documentation and examples for Julia'
  depends=(${MINGW_PACKAGE_PREFIX}-julia)

  install -d "$pkgdir${MINGW_PREFIX}/share/doc"
  cp -r ${_sourcedir}/doc "$pkgdir${MINGW_PREFIX}/share/doc/${_realname}"
  rm -rf "$pkgdir${MINGW_PREFIX}/share/doc/${_realname}/man"
  install -Dm644 ${_sourcedir}/LICENSE.md \
    "$pkgdir${MINGW_PREFIX}/share/licenses/julia-docs/LICENSE.md"
}

# template start; name=mingw-w64-splitpkg-wrappers; version=1.0;
# vim: set ft=bash :

# generate wrappers
for _name in "${pkgname[@]}"; do
  _short="package_${_name#${MINGW_PACKAGE_PREFIX}-}"
  _func="$(declare -f "${_short}")"
  eval "${_func/#${_short}/package_${_name}}"
done
# template end;
