# Maintainer: Yichao Yu <yyc1992@gmail.com>
# Contributor: Lex Black <autumn-wind at web dot de>
# Contributor: Michael Jakl <jakl.michael@gmail.com>
# With contributions from many kind people at https://aur.archlinux.org/packages/julia-git/

BUILD_DOC=1

pkgbase=julia-git
pkgname=(julia-git julia-git-package-env)

if [[ $CARCH != x86_64 ]]; then
  BUILD_DOC=0
fi

if ((BUILD_DOC)); then
  pkgname+=('julia-git-docs')
fi

case "$CARCH" in
  x86_64)
    _soarch=64
    ;;
  i686)
    _soarch=32
    ;;
  aarch64)
    _soarch=64
    ;;
  armv7h)
    _soarch=32
    ;;
esac

epoch=1
pkgver=1.14.0.DEV.2881.ge9cc45c5417
pkgrel=1
pkgdesc="Julia is a high-level, high-performance, dynamic programming language."
arch=('i686' 'x86_64' 'armv7h' 'aarch64')
url="http://julialang.org"
license=('GPL')
_soname_deps=(libcurl.so libgit2.so libopenlibm.so libssh2.so libcrypto.so libssl.so)
depends_libs=(arpack fftw gmp libunwind mpfr pcre2 suitesparse
              openspecfun libutf8proc libblastrampoline
              openssl zlib 7zip libnghttp2 ca-certificates-utils lld
              blas-openblas)
case "$CARCH" in
  x86_64)
    depends_libs=("${depends_libs[@]}" openblas64-git blas64-openblas)
    ;;
  aarch64)
    depends_libs=("${depends_libs[@]}" openblas64-git blas64-openblas)
    ;;
  i686)
    depends_libs=("${depends_libs[@]}" openblas-git)
    ;;
  armv7h)
    depends_libs=("${depends_libs[@]}" openblas-git)
    ;;
esac
makedepends=("${depends_libs[@]}" llvm-julia-git gcc-fortran git patchelf python proot
             "${_soname_deps[@]}" julia-git-common-scripts tar)
# Both debug and strip cause pacman to edit the ELF files and breaking them
# for loading.
options=('!debug' '!strip' '!buildflags')
_patches=(
  0001-Force-enable-GDB-debug-info-registration.patch
  0002-Fix-source-file-paths.patch
  0003-Clear-soname-and-hard-code-system-lib-path.patch
  0004-Support-loading-extensions-from-STDLIB.patch
  0005-julia-git-add-a-safeguard-for-bad-unwinding.patch
  0006-Disable-UCX-signal-handler.patch
  0007-julia-git-Better-support-for-loading-packages-from-s.patch
  0008-Reduce-likelyhood-of-symbol-conflict.patch
  0009-codegen-add-support-for-llvm-22.patch
  0010-Fix-gcc_s-search.patch
  0011-llvm-Update-to-LLVM-22.1.8.patch
)
source=('git+https://github.com/JuliaLang/julia'
        "${_patches[@]}"
        julia-preinstall.hook
        julia-postinstall.hook
        arch-source-translate.cpp
        0001-Disable-upgrade-of-stdlib-package.diff
        0002-Hard-code-7z-and-zstd-path.diff
        download_curl.diff)
sha512sums=('SKIP'
            '6f436f00b5ba254b569be206c818fc7c9a9f8638d3399377090b33addd54d91d93eeeb03d176436f77dcda43a870e372e50db7f52afcd81aa4197f4b505d9a64'
            '4e0e2985f0b1597fa0fd1801ed224ad073bb8cbda52db3dc9852e0ba16090a57d8b6b5ff55b841a3f44caeaeddce2b08b7ae5ce6268524e45edbd8b6a4b67db1'
            '8e87d17b513db496dbed95f21a7c09b5740d10cb2e40e4a19ae497d868ae4c650e1ed6aba4a559f4405d83a4b1a4470c248b0a973596382d885dbae4f3ba837d'
            'c2685db7af8bcc1b2843ec5f7eb7fe3e2ce8169039358b853720323a6ea25d396686ff6446636856fb80e03d9c01d8206c729adbe89dd2391714a998901b4519'
            'a2268af9238a0d3fd140ebb2bf728ac1d9099dd55bb17c8bdd1a1b81c42c57965c3e6f07bc7e0eeb8e5aa768249dee81eaa5999405c18793e9c8d255acb8c740'
            'd5e82828dff8cf5a5fd2de9f0f111c68a2efcf40f6aee1a724fa5a3165fca1f7da53be5b3f37a5dada84f82c5bcbd13cbf06a676d730622fa7c3e90a2826e837'
            '1b4e625cc3cb6fe17a5a4b4b5382a3357c4bf0ef674805bdbd00befcf215ee792af26bd5ddf04d3dfee07af2e35c25b988d8e7a67a7c646c6cc62dda5575ff76'
            '53c1b8ea9ab20aff83447f8b9188bf8d6b3defbc56f41a931bf3fd2e12794b0ab8956787399277563d06a2f6115aeef59aa97401b0615231cc05c587a44f98f1'
            '823162ed5d80fac4301366fbadaa60861570d7053f76f42aa676da66cd86395027f9743280afa93aa15e244450c98e3ca335b3ca38b5963cb14955c1540de716'
            '81c5036882322d1469bb407ef70a12919b4591bbdad18f8f4ad644e306837e1812db7a1c1d973c497ecdde6c0b7059205013ecd3283bc3156cec7dd96fd26141'
            'f2dc764c7bf13306014209269abb21c86af3a5c1bccb7f6ded67b0ee545d1c245a030de3796b3bf5f08294ae97d1b0bcabdb96d4c486a12ce146cb52f0ba0003'
            '997f22456f175c6cc03b2dd407b7584df514bc4c91602ef011b93d8b558f7c587b4e216535e573f6063f3a606f88c48dee3041a5122a7dbf0bee6d1bc8df15b4'
            'a668a9bd01cec8f53f457d9124107a230260c79fd57cbce4c4bf80e3451758d8e67263faa3f9d8b3da0c10bffbe29e4032106881ebe682c7f66414d8989638be'
            'c2da7461c53e56293d35581cb4aa2500ef9a98e52a354bfa9271f44bd768ed77c5b362e304e0ab467fb286d2198f3e28cf91089e8773ebcfc85e294223a12f0e'
            '99b91e921e730016e758dba10fb80436c0bb595789c941536d4533fd053caeff1100c06d1813cd0326790c85a988f1c6e282bb185eba7991b0485d529d35ba2c'
            '6184ec0c916cf51a478760dba85d3a140077ec073a49aac1b95d9fd3f46b4ecefad44725729adfc4af576e6940f65ee8205bce153db1e9fe8fb432c6316f90c5'
            '5be40dcb72428885c06c8353019bd8fac0ea186a7536cf2bab2554d2724fb3d4a5b0b3f61727428e5cf7906f14a213f08dcb238b5bd10d408d86669e2c93ca78')

_versioned_llvm=

pkgver() {
  cd julia

  last_tag=$(git describe --tags --abbrev=0)

  #collect the contents
  commit_short=$(git rev-parse --short HEAD)
  verchanged=$(git blame -L ,1 -sl -- VERSION | cut -f 1 -d " ")
  build_number=$(git rev-list --count HEAD "^$verchanged")
  # Combine version from VERSION file with rev-count and latest commit
  printf "%s.%s.g%s" "$(git show HEAD:VERSION | sed 's/-/./g')" \
         "$build_number" "$commit_short"
}

_LLVM_CONFIG=llvm-config
if [[ -n $_versioned_llvm ]]; then
  _LLVM_CONFIG=llvm-config-${_versioned_llvm}
fi

julia_opts=(prefix=/usr sysconfdir=/etc
            USE_SYSTEM_LIBWHICH=0
            USE_SYSTEM_CSL=1
            USE_SYSTEM_LLVM=1
            USE_SYSTEM_LIBUNWIND=1
            USE_SYSTEM_PCRE=1
            USE_SYSTEM_OPENLIBM=1
            USE_SYSTEM_BLAS=1
            USE_SYSTEM_LAPACK=1
            USE_SYSTEM_GMP=1
            USE_SYSTEM_MPFR=1
            USE_SYSTEM_LIBSUITESPARSE=1
            USE_SYSTEM_LIBBLASTRAMPOLINE=1
            USE_SYSTEM_UTF8PROC=1
            USE_SYSTEM_OPENSSL=1
            USE_SYSTEM_LIBSSH2=1
            USE_SYSTEM_NGHTTP2=1
            USE_SYSTEM_CURL=1
            USE_SYSTEM_LIBGIT2=1
            USE_SYSTEM_PATCHELF=1
            USE_SYSTEM_ZLIB=1
            USE_SYSTEM_ZSTD=1
            USE_SYSTEM_P7ZIP=1
            USE_SYSTEM_LLD=1
            USE_INTEL_JITEVENTS=0
            USE_LLVM_SHLIB=1
            USE_BINARYBUILDER=0
            WITH_TERMINFO=0
            LLVM_USE_CMAKE=0 # Workaround LLVM linking with system LLVM
            MSYS_NONEXISTENT_SYMLINK_TARGET_FIX=true # fix compilation
            LLVM_CONFIG=${_LLVM_CONFIG})

_x86_target='generic,opt_size;haswell,clone_all,-rdrnd;skylake,base(1),-rdrnd,-rdseed,-rtm;cannonlake,base(1),-rdrnd,-rdseed,-rtm'
_arm_target='armv7-a;armv7-a,neon;armv7-a,neon,vfp4'
_aa64_target='generic;generic,v8.2a;apple-m1,clone_all'

case "$CARCH" in
  x86_64)
    _cpu_target="${_x86_target}"
    julia_opts=("${julia_opts[@]}" MARCH=x86-64
                USE_BLAS64=1
                LIBBLASNAME=libopenblas64_
                LIBBLAS=-lopenblas64_
                LIBLAPACKNAME=libopenblas64_
                LIBLAPACK=-lopenblas64_)
    ;;
  i686)
    _cpu_target="${_x86_target}"
    julia_opts=("${julia_opts[@]}" MARCH=pentium4
                USE_BLAS64=0
                LIBBLASNAME=libopenblas
                LIBBLAS=-lopenblas
                LIBLAPACKNAME=libopenblas
                LIBLAPACK=-lopenblas)
    ;;
  aarch64)
    _cpu_target="${_aa64_target}"
    julia_opts=("${julia_opts[@]}" MARCH=armv8-a
                USE_BLAS64=1
                LIBBLASNAME=libopenblas64_
                LIBBLAS=-lopenblas64_
                LIBLAPACKNAME=libopenblas64_
                LIBLAPACK=-lopenblas64_)
    ;;
  armv7h)
    _cpu_target="${_arm_target}"
    julia_opts=("${julia_opts[@]}" MARCH=armv7-a
                USE_BLAS64=0
                LIBBLASNAME=libopenblas
                LIBBLAS=-lopenblas
                LIBLAPACKNAME=libopenblas
                LIBLAPACK=-lopenblas)
    ;;
esac
julia_opts=("${julia_opts[@]}" JULIA_CPU_TARGET="${_cpu_target}")

_apply_patch() {
  echo "Applying $1"
  patch -Np1 --no-backup-if-mismatch < "../$1"
}

_patch_suitesparse() {
  echo "Patching suitesparse version"
  local cholmod_libs=(/usr/lib/libcholmod.so.*.*.*)
  local cholmod_maj_ver=
  local cholmod_min_ver=
  local cholmod_patch_ver=
  local lib
  for lib in "${cholmod_libs[@]}"; do
    [[ $lib =~ /usr/lib/libcholmod\.so\.([0-9]+)\.([0-9]+)\.([0-9]+) ]] || continue
    if [[ -z $cholmod_maj_ver ]]; then
      cholmod_maj_ver=${BASH_REMATCH[1]}
      cholmod_min_ver=${BASH_REMATCH[2]}
      cholmod_patch_ver=${BASH_REMATCH[2]}
    else
      echo "WARNING: Multiple versions of cholmod libraries found" >&2
    fi
  done
  for d in usr/share/julia/stdlib/v*/SparseArrays; do
    (
      cd "$d"
      # Patch the code to assume newer cholmod version. This is generally unsafe
      # but should be fine for 3->4 according to the suitesparse changelog.
      for f in src/solvers/wrappers.jl; do
        echo "Updating $d/$f"
        sed -i -e "s/\(CHOLMOD_MAIN_VERSION *= *\)[0-9]*/\1${cholmod_maj_ver}/" "$f"
        sed -i -e "s/\(CHOLMOD_SUB_VERSION *= *\)[0-9]*/\1${cholmod_min_ver}/" "$f"
        sed -i -e "s/\(CHOLMOD_SUBSUB_VERSION *= *\)[0-9]*/\1${cholmod_patch_ver}/" "$f"
      done
    )
  done

  sed -i -e 's/^[[:blank:]]*\$(eval.*libcholmod_cuda/# &/' base/Makefile
  sed -i -e 's/^[[:blank:]]*\$(eval.*libspqr_cuda/# &/' base/Makefile
}

prepare() {
  rm -rf bin/
  mkdir -p bin/

  for p in cc c++ gcc g++; do
    cat > bin/$p <<EOF
exec /usr/bin/$p "\${@/#-O0/-Og}" -fasynchronous-unwind-tables -ffile-prefix-map="${srcdir}=${DBGSRCDIR:-/usr/src/debug}"
EOF
    chmod +x bin/$p
  done

  cat > bin/patchelf <<EOF
/usr/bin/patchelf "$@"
exit 0
EOF
  chmod +x bin/patchelf

  cd julia

  git reset --hard HEAD
  git clean -fdx

  for p in "${_patches[@]}"; do
    _apply_patch "$p"
  done
  make "${julia_opts[@]}" julia-stdlib
  (
    cd usr/share/julia/stdlib/v*/Pkg

    patch -Np1 --no-backup-if-mismatch < "$srcdir/0001-Disable-upgrade-of-stdlib-package.diff"
    patch -Np1 --no-backup-if-mismatch < "$srcdir/0002-Hard-code-7z-and-zstd-path.diff"
  )
  (
    cd usr/share/julia/stdlib/v*/Downloads
    patch -Np0 --no-backup-if-mismatch < "$srcdir/download_curl.diff"
  )
  for f in usr/share/julia/stdlib/v*/*/*Artifacts.toml; do
    echo "Clearing $f"
    echo > "$f"
  done
  _patch_suitesparse
  # Try disabling threading when generating precompilations
  # The module initialization code seems to have some bug that is triggered
  # reliably on aarch64 on the build machine.
  sed -i -e 's/debug_output = devnull/debug_output = stdout/' \
      -e 's/cpu-target=native/cpu-target=native -t1,0/' contrib/generate_precompile.jl
  sed -i -e 's/-fno-omit-frame-pointer/-fomit-frame-pointer/g' */Makefile
  sed -i -e 's/\(symlink_system_library,CSL,libquadmath,[0-9]*\))/\1,ALLOW_FAILURE)/g' base/Makefile
  # compile_commands.json was treated as a PHONY target and therefore will be regenerated
  # even if it exists. The generation also break if there are two version of it running
  # in parallel (which happens when we compile release and debug build in parallel)
  sed -i -e '/^\.PHONY:/s/compile_commands\.json/compile_commands.json.tmp/' \
      src/Makefile src/flisp/Makefile src/support/Makefile
}

_with_git_url_override() {
  # doc build tries to read the remote for the current build directly
  # Make it happy by setting the remote url temporarily
  local _orig_remote=$(git config --get remote.origin.url)
  git config remote.origin.url https://github.com/JuliaLang/julia
  if ! "$@"; then
    git config remote.origin.url "$_orig_remote"
    return 1
  fi
  git config remote.origin.url "$_orig_remote"
}

build_in() {
  cd "$1"

  export JL_MAKEPKG_SRCDIR="${PWD}"

  opts=("${@:3}")
  export PATH="${srcdir}/bin:${PATH}"
  if [[ $CARCH = i686 ]]; then
    CFLAGS="${CFLAGS//-march=i686/-march=pentium4} -march=pentium4"
    CXXFLAGS="${CXXFLAGS//-march=i686/-march=pentium4} -march=pentium4"
  fi
  CFLAGS+=" -ffile-prefix-map=${srcdir}=${DBGSRCDIR:-/usr/src/debug}"
  CXXFLAGS+=" -ffile-prefix-map=${srcdir}=${DBGSRCDIR:-/usr/src/debug}"
  export CFLAGS+=' -Wno-pedantic -Wno-clobbered'
  export CXXFLAGS+=' -Wno-pedantic -Wno-clobbered'
  export LDFLAGS+=' -lzstd'

  ver=$(cat VERSION | cut -f 1-2 -d '.')

  find -name 'compile_commands.json*' -exec rm {} \;

  # These are to workaround bugs in the hand-made build system that can't handle
  # parallel build properly.
  make "${opts[@]}" -C base version_git.jl.phony
  make "${opts[@]}" -C deps
  make "${opts[@]}" -C src jl_internal_funcs.inc
  make "${opts[@]}" -C src compile-database
  make "${opts[@]}" julia-cli-release
  # I'm a bit too lazy to fix this properly
  # so I'm just going to create this missing symlink
  ln -sf /usr/lib/libgcc_s.so.1 usr/lib/julia/
  ln -sf /usr/lib/libstdc++.so.6 usr/lib/
  ln -sf /usr/lib/libatomic.so usr/lib/
  # if [[ "$CARCH" = x86_64 ]]; then

  # Currently only the x86 build machine
  # has enough memory to compile release and debug build in parallel...
  make "${opts[@]}" release debug

  # else
  #   make "${opts[@]}" release
  #   make "${opts[@]}" debug
  # fi

  # TODO docless build
  JL_MAKEPKG_SRCDIR= _with_git_url_override make "${opts[@]}" docs

  # Check to detect issues like JuliaLang/julia#13820
  LD_PRELOAD= JL_MAKEPKG_SRCDIR= usr/bin/julia -e '0'
  LD_PRELOAD= JL_MAKEPKG_SRCDIR= usr/bin/julia-debug -e '0'
}

build() {
  if [[ $(vercmp $(g++ -dumpversion) 10) = -1 ]]; then
    g20=gnu++2a
  else
    g20=gnu++20
  fi
  g++ -fPIC -Wall -Wextra -shared -o libarch-source-translate.so -O2 \
      -std=$g20 arch-source-translate.cpp
  # _ld_preload="${srcdir}/libarch-source-translate.so"
  # if [[ -n $LD_PRELOAD ]]; then
  #   _ld_preload="${_ld_preload}:$LD_PRELOAD"
  # fi
  (LD_PRELOAD="${_ld_preload}" build_in julia $BUILD_DOC "${julia_opts[@]}")
}

_source_files() {
  # Copied from /usr/share/makepkg/tidy/strip.sh
  LANG=C readelf "$1" --debug-dump 2>/dev/null | \
    awk '/DW_AT_name +:/{name=$NF}/DW_AT_comp_dir +:/{{if (name == "<artificial>") next}{if (name !~ /^[<\/]/) {printf "%s/", $NF}}{print name}}'
}

package-julia-in() {
  _llvm_ver=$(${_LLVM_CONFIG} --version)
  [[ $_llvm_ver =~ ^([0-9]*).* ]]
  llvm_maj_ver=${BASH_REMATCH[1]}
  ((next_llvm_maj=llvm_maj_ver + 1))

  arch=('i686' 'x86_64' 'armv7h' 'aarch64')
  depends=("${depends_libs[@]}"
           "llvm-libs-julia-git>=${llvm_maj_ver}.0"
           "llvm-libs-julia-git<${next_llvm_maj}.0"
           julia-git-common-scripts hicolor-icon-theme xdg-utils)
  opts=("${@:2}")

  cd "$1"

  export JL_MAKEPKG_SRCDIR="${PWD}"
  export PATH="${srcdir}/bin:${PATH}"

  # TODO docless build
  # if ((BUILD_DOC)); then
  # Install the debug version first. If there's any file conflict
  # due to build system bugs, I want the final version to be the release one.

  # Delete precompiled environment since it seems to be picking up the one compiled
  # for the wrong julia build during document generation.
  rm -rf doc/deps/compiled
  _with_git_url_override \
    make install DESTDIR="$pkgdir" "${opts[@]}" JULIA_BUILD_MODE=debug
  rm -rf doc/deps/compiled
  _with_git_url_override \
    make install DESTDIR="$pkgdir" "${opts[@]}" JULIA_BUILD_MODE=release
  # else
  #   make install-nodoc DESTDIR="$pkgdir" "${opts[@]}"
  #   # Manually install man pages
  #   mkdir -p "$pkgdir"/usr/share/man/man1/
  #   install -m644 -t "$pkgdir"/usr/share/man/man1/ usr/share/man/man1/julia.1
  # fi

  # Remove doc files (should be non for nodoc install)
  rm -rf "$pkgdir/usr/share/doc/julia"

  # Running julia requires this link
  ln -sf /usr/lib/libstdc++.so.6 "${pkgdir}"/usr/lib/
  ver=$("$pkgdir/usr/bin/julia" \
          --startup-file=no \
          -e 'print(VERSION.major, ".", VERSION.minor, ".", VERSION.patch)')
  ver_short=$("$pkgdir/usr/bin/julia" \
                --startup-file=no \
                -e 'print(VERSION.major, ".", VERSION.minor)')
  stdlib_dir="$pkgdir/usr/share/julia/stdlib/v$ver_short"
  builtin_pkgs=()
  for pkg in $(ls -1 "$stdlib_dir"); do
    if [[ -f "$stdlib_dir/$pkg/Project.toml" ]]; then
      builtin_pkgs=("${builtin_pkgs[@]}" "julia-git-${pkg,,}" "julia-git-${pkg,,}-src")
      echo "$pkg"
    fi
    # Keep a list of the builtin stdlibs so that we can compile these as a whole
    # in a single package. Note that even though these are builtin,
    # not all of them are in the system image.
  done > "$pkgdir/usr/share/julia/builtin_stdlib.v$ver_short"
  provides=("julia=2:$ver" "${builtin_pkgs[@]}")
  conflicts=('julia' "${builtin_pkgs[@]}")
  replaces=("${builtin_pkgs[@]}")

  sed -e "s|@VER@|$ver_short|g" "${srcdir}/julia-preinstall.hook" |
    install -Dm644 /dev/stdin "${pkgdir}/usr/share/libalpm/hooks/julia-preinstall.hook"
  sed -e "s|@VER@|$ver_short|g" "${srcdir}/julia-postinstall.hook" |
    install -Dm644 /dev/stdin "${pkgdir}/usr/share/libalpm/hooks/julia-postinstall.hook"

  mkdir -p "${pkgdir}/usr/share/julia/compiled/v$ver_short"

  mkdir -p "${pkgdir}/usr/share/julia/contrib"
  install -m644 -t "${pkgdir}/usr/share/julia/contrib" contrib/generate_precompile.jl

  # From ca-certificates-utils, needed by Downloads stdlib
  ln -sf /etc/ssl/cert.pem "${pkgdir}/usr/share/julia/cert.pem"

  rm "$pkgdir"/usr/lib/julia/libccalltest.so.debug # Remove debug testing library

  # Without stripping, makepkg doesn't copy the source for us...
  dbgsrcdir="${DBGSRCDIR:-/usr/src/debug}"
  for binary in usr/bin/julia usr/bin/julia-debug \
                              usr/lib/libjulia.so usr/lib/libjulia-debug.so \
                              usr/lib/julia/libjulia-internal.so \
                              usr/lib/julia/libjulia-internal-debug.so; do
    binary="${pkgdir}/${binary}"
    ls "$binary"
    # copy source files to debug directory
    local f t
    while IFS= read -r t; do
      f=${t/${dbgsrcdir}/"$srcdir"}
      if ! [[ -f "$f" ]]; then
        echo "Cannot find source file: '$f'"
        continue
      fi
      case "${t%/*}" in
        "${srcdir}"*)
          echo "Source file path not mapped: '${t%/*}'."
          continue
          ;;
      esac
      mkdir -p "${pkgdir}/${t%/*}"
      cp -- "$f" "${pkgdir}/${t%/*}"
    done < <(_source_files "$binary")
  done
  # Files that are not compiled directly aren't being copied by the code above.
  # This include all headers as well as some cpp files
  #   (e.g. `cgutils.cpp`, `processor_*.cpp` etc)
  # that are included from other files. Copy these directly for now.
  cp src/*.{c,cpp} "${pkgdir}/${dbgsrcdir}/julia/src/"
  (
    cd "${pkgdir}/usr/include/julia"
    mkdir -p "${pkgdir}/${dbgsrcdir}/julia/src/"
    for f in *; do
      ln -sf "/usr/include/julia/$f" "${pkgdir}/${dbgsrcdir}/julia/src/$f"
    done
  )

  # The ones that julia build system build does not seem to work at the moment.
  # rm -rf "${pkgdir}/usr/share/julia/compiled/v$ver_short/"*
  env JULIA_PRECOMPILE_STDLIB_DIR="/usr/share/julia/stdlib/v$ver_short" \
      JULIA_CPU_TARGET="${_cpu_target}" \
      proot -b "${pkgdir}/usr/share/julia/:/usr/share/julia/" \
      "${pkgdir}/usr/bin/julia" --startup-file=no \
      "/usr/lib/julia/julia-compile-pkgs.jl" /usr/share/julia
  env JULIA_PRECOMPILE_STDLIB_DIR="/usr/share/julia/stdlib/v$ver_short" \
      JULIA_CPU_TARGET="${_cpu_target}" \
      proot -b "${pkgdir}/usr/share/julia/:/usr/share/julia/" \
      "${pkgdir}/usr/bin/julia-debug" --startup-file=no \
      "/usr/lib/julia/julia-compile-pkgs.jl" /usr/share/julia
  mkdir -p "${pkgdir}/usr/lib/julia/arch-compiled/julia/"
  mv "${pkgdir}/usr/share/julia/compiled/v$ver_short/"* \
     "${pkgdir}/usr/lib/julia/arch-compiled/julia/"

  chmod -R go-w "${pkgdir}/usr/lib/julia/arch-compiled/julia/"

  # The ji file records the exact time stamps so we need to fix those in post_install
  (
    echo "_fix_timestamps() {"
    cd "${pkgdir}"
    find usr/share/julia/stdlib -type f -exec \
         sh -c 'echo "  touch -c -d \"$(stat -c %y "{}")\" \"{}\""' \;
    echo "}"

    echo "post_install() {"
    echo "  _fix_timestamps"
    echo "}"

    echo "post_upgrade() {"
    echo "  _fix_timestamps"
    echo "}"
  ) > "${startdir}/install.pkg"
  true && install=install.pkg

  # Manually filling in the soname dependencies since makepkg doesn't recognize the symlink
  # julia uses to specify the soname
  for libname in "${_soname_deps[@]}"; do
    local filename="${pkgdir}/usr/lib/julia/${libname}"
    [[ -f "${filename}" ]] || {
      echo "Cannot find library: ${libname} in ${pkgdir}/usr/lib/julia/"
      exit 1
    }
    local soarch=$(LC_ALL=C readelf -h "$filename" 2>/dev/null |
                     sed -n 's/.*Class.*ELF\(32\|64\)/\1/p')
    [[ -n "$soarch" ]] || [[ "$soarch" != "$_soarch" ]] || {
      echo "SO arch of library ${libname}: '${soarch}' does not match '${_soarch}'"
      exit 1
    }

    local sofile=$(LC_ALL=C readelf -d "$filename" 2>/dev/null |
                     sed -n 's/.*Library soname: \[\(.*\)\].*/\1/p')
    if [[ -z "$sofile" ]]; then
      echo "Library ${libname}: is not versioned"
      exit 1
    fi

    local soversion="${sofile##*\.so\.}"
    depends+=("${libname}=${soversion}-${soarch}")
  done
  rm "${pkgdir}"/usr/lib/libstdc++.so.6
  # We patched references to these out in julia code
  rm -rf "${pkgdir}"/usr/libexec/julia/
}

package_julia-git() {
  # export LD_PRELOAD="${srcdir}/libarch-source-translate.so:$LD_PRELOAD"
  package-julia-in julia "${julia_opts[@]}"
  if [[ "$CARCH" = x86_64 ]]; then
    replaces=(julia-git-avx2)
  fi
}

package_julia-git-package-env() {
  backup=(usr/lib/julia/.package-precompile-env)
  pkgdesc+=" (Package precompilation environment)"

  mkdir -p "${pkgdir}/usr/lib/julia/"
  cat > "${pkgdir}/usr/lib/julia/.package-precompile-env" <<EOF
export JULIA_CPU_TARGET="${_cpu_target}"
if ((\$(getconf PAGESIZE) * \$(getconf _PHYS_PAGES) > 100000000000)); then
  export JULIA_PRECOMPILE_NPROCESS=\$(nproc)
else
  export JULIA_PRECOMPILE_NPROCESS=3
fi
EOF
}

package_julia-git-docs() {
  arch=('any')
  pkgdesc+=" (Documents)"
  provides=('julia-docs' 'julia-doc')
  conflicts=('julia-docs' 'julia-doc' 'julia-git-doc' 'julia-doc-git')
  replaces=('julia-git-doc' 'julia-doc-git')

  cd julia/doc/_build

  mkdir -p "$pkgdir"/usr/share/doc/julia/
  cp -dpr --no-preserve=ownership html "$pkgdir"/usr/share/doc/julia/
  find "$pkgdir/usr/share/doc/julia/" -type f -exec sed -i -e "s|$srcdir/julia||g" '{}' \+
}
