# Maintainer: Maksim Bondarenkov <maksapple2306@gmail.com>
# Maintainer: Alexey Pavlov <alexpux@gmail.com>
# Contributor: Zion Nimchuk <zionnimchuk@gmail.com>
# Contributor: Mateusz Mikuła <mati865@gmail.com
# Contributor: Philippe Renon <philippe_renon@yahoo.fr>

_bootstrapping=yes
if [[ $MINGW_PACKAGE_PREFIX == *-clang-* ]]; then
  _bootstrapping=no
fi
if [[ $CARCH == x86_64 ]]; then
  _pgo=1
fi
if [[ ${CARCH} != i686 && ${MSYSTEM} != MINGW64 ]]; then
  _wasm=1
fi

rust_dist_server=https://static.rust-lang.org/dist
#rust_dist_server=https://dev-static.rust-lang.org/dist/2025-10-27

_realname=rust
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}"
         $([[ ${CARCH} == i686 ]] || echo "${MINGW_PACKAGE_PREFIX}-rust-src")
         $((( _wasm )) && echo \
           "${MINGW_PACKAGE_PREFIX}-rust-wasm" \
           "${MINGW_PACKAGE_PREFIX}-rust-emscripten"))
pkgver=1.91.0
pkgrel=2
pkgdesc="Systems programming language focused on safety, speed and concurrency (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://www.rust-lang.org/"
msys2_repository_url="https://github.com/rust-lang/rust"
msys2_references=(
  'anitya: 7635'
  'archlinux: rust'
  "cpe: cpe:/a:rust-lang:rust"
  'gentoo: dev-lang/rust'
)
license=('spdx:Apache-2.0 AND MIT')
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-clang"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-curl"
             "${MINGW_PACKAGE_PREFIX}-libffi"
             "${MINGW_PACKAGE_PREFIX}-libgit2"
             "${MINGW_PACKAGE_PREFIX}-libssh2"
             "${MINGW_PACKAGE_PREFIX}-llvm"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-openssl"
             "${MINGW_PACKAGE_PREFIX}-pkgconf"
             "${MINGW_PACKAGE_PREFIX}-python"
             "${MINGW_PACKAGE_PREFIX}-sqlite3"
             $([[ "$_bootstrapping" == "no" ]] && echo "${MINGW_PACKAGE_PREFIX}-rust")
             "${MINGW_PACKAGE_PREFIX}-xz"
             "${MINGW_PACKAGE_PREFIX}-zstd"
             "${MINGW_PACKAGE_PREFIX}-zlib"
             $((( _wasm )) && echo \
               "${MINGW_PACKAGE_PREFIX}-emscripten" \
               "${MINGW_PACKAGE_PREFIX}-wasi-libc" \
               "${MINGW_PACKAGE_PREFIX}-wasm-component-ld")
             $((( _pgo )) && echo \
               "${MINGW_PACKAGE_PREFIX}-compiler-rt" \
               "${MINGW_PACKAGE_PREFIX}-lld"))
source=("${rust_dist_server}/${_realname}c-${pkgver}-src.tar.xz"{,.asc}
        "bootstrap.toml"
        "bootstrap-wasm.toml"
        "0001-rustc-llvm-fix-libs.patch"
        "0004-compiler-Use-wasm-ld-for-wasm-targets.patch"
        "0008-disable-self-contained-for-gnu-targets.patch"
        "0014-rustc-perf-less-verbose.patch"
        "0016-allow-shared-llvm-for-all.patch"
        # patches in case of doing PGO for LLVM with opt-dist
        #"0015-lesser-llvm-build.patch"
        #"https://patch-diff.githubusercontent.com/raw/rust-lang/rust/pull/143898.patch"
)
noextract=(${_realname}c-${pkgver}-src.tar.xz)
sha256sums=('9b94161dba3aa32192e0e75f7891912d98095ffb86087b07a05af35a0265a938'
            'SKIP'
            'c43af449a04bf3c5feb61356c537a617c663b5a61937686570feca3d3719a2b5'
            'd693577fabe39a3046cd44fd002adf9557de6883eaea9007eae7f8372295ea0e'
            '7cb1773c288ffb1c1e751edc49b1890c84bf9c362742bc5225d19d474edb73a0'
            '56882f1a0f1404c10c7726d6cc37444f2b343e72b969badfcb43760f80db0f32'
            '87b68c2dfbe996d3ef439278e1ac90997fc4ea192f449e8f00262360a551386a'
            '6a8d987186785901d8a6e347d6ec3bccd84c869c9fa1a57cb9a30c8f6a3ce3ac'
            'f891ce9c3b040a17c8764d8dcbd78d39be089bffbfb884050f2a612a923536c6')
validpgpkeys=('108F66205EAEB0AAA8DD5E1C85AB96E6FA1BE5FE'  # Rust Language (Tag and Release Signing Key) <rust-key@rust-lang.org>
              '474E22316ABF4785A88C6E8EA2C794A986419D8A'  # Tom Stellard <tstellar@redhat.com>
              'B6C8F98282B944E3B0D5C2530FC3042E345AD05D') # Hans Wennborg <hans@chromium.org>

# =========================================== #
#   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 sure the duplication in rust-wasm is found
COMPRESSZST+=(--long)

prepare() {
  plain "Extracting ${_realname}c-${pkgver}-src.tar.xz"
  tar -xJf ${_realname}c-${pkgver}-src.tar.xz || true

  cd ${_realname}c-${pkgver}-src
  if [[ ${CARCH} == i686 ]]; then
    apply_patch_with_msg \
      0001-rustc-llvm-fix-libs.patch
  fi

  # 0008-disable-self-contained-for-gnu-targets.patch allows self-contained for non-windows-gnu targets
  apply_patch_with_msg \
    0008-disable-self-contained-for-gnu-targets.patch \
    0004-compiler-Use-wasm-ld-for-wasm-targets.patch \
    0014-rustc-perf-less-verbose.patch \
    0016-allow-shared-llvm-for-all.patch
}

build() {
  cd "${_realname}c-${pkgver}-src"

  # We have to do the following because rust doesn't count x86_64-w64-mingw32 as a target triple
  if [[ $MINGW_PACKAGE_PREFIX == *-clang-* ]]; then
    export OSTYPE="$CARCH-pc-windows-gnullvm"
  else
    export OSTYPE="$CARCH-pc-windows-gnu"
  fi

  if [[ $MINGW_PACKAGE_PREFIX != *-clang-aarch64 ]]; then
    # Use $CFLAGS for $OSTYPE only
    export CFLAGS_${OSTYPE//-/_}="$CFLAGS"

    # Remove unsupported options for target wasm32-*
    local _unsupported_options="-march=nocona -msahf"
    export CFLAGS="${CFLAGS#$_unsupported_options}"
  fi

  # For a faster build:
  # - add --disable-docs and --disable-compiler-docs
  # - compile only rustc by removing --enable-extended
  # - run makepkg-mingw with --nocheck
  # - remove --stage 2

  export RUST_BACKTRACE=1
  export RUST_LOG=info
  # force some system libraries
  export LIBSQLITE3_SYS_USE_PKG_CONFIG=1
  export LIBSSH2_SYS_USE_PKG_CONFIG=1

  # substitute the values in bootstrap.toml
  export MSYS2_ENV_CONV_EXCL='INSTALL_PREFIX'
  export INSTALL_PREFIX="${MINGW_PREFIX}"
  export PKGREL="${pkgrel}"
  envsubst < ../bootstrap.toml > bootstrap.toml
  envsubst < ../bootstrap-wasm.toml > bootstrap-wasm.toml

  if [ "${_bootstrapping}" = "no" ]; then
    sed -i '/^\[build\]/,/^$/ s|^#||g' bootstrap{,-wasm}.toml
  fi
  # generate debuginfo only for non-i686 targets
  if check_option "debug" "y" && [ "${CARCH}" != i686 ]; then
    sed -i 's/^#debug/debug/g' bootstrap{,-wasm}.toml
  fi

  # Add tools and enable LTO for non-i686
  if [[ ${CARCH} != i686 ]]; then
    sed -i -e '/tools = \[/a\  "clippy", "rustdoc", "rustfmt", "rust-analyzer-proc-macro-srv", "analysis", "src",' \
           -e 's/#lto/lto/' bootstrap.toml
  fi

  if (( _pgo )); then
    sed -i -e 's/#use-lld/use-lld/' \
           -e 's/#link-shared/link-shared/' bootstrap.toml
    # build opt-dist tool which manages PGO build
    python x.py build opt-dist --target="$OSTYPE"
    local _pgo_opts=(--target-triple="$OSTYPE"
                     --checkout-dir="$PWD"
                     --llvm-dir="${MINGW_PREFIX}"
                     --build-llvm=false
                     --python="${MINGW_PREFIX}/bin/python.exe"
                     --artifact-dir=opt-artifacts-${MSYSTEM}
                     --build-dir=build-${MSYSTEM})
    # CLANG* don't have prebuilt stage0
    if [[ ${_bootstrapping} == no ]]; then
      _pgo_opts+=(--stage0-root="${MINGW_PREFIX}")
    fi
    # run opt-dist to get rustc optimized with PGO. add linker flag for InitSecurityInterfaceA symbol
    CXXFLAGS="$CXXFLAGS -fuse-ld=lld" \
    DESTDIR="$PWD/build-$MSYSTEM/dest-rust" \
    RUSTFLAGS="${RUSTFLAGS/+crt-static/-crt-static} -C link-arg=-lsecur32" \
    build-${MSYSTEM}/${OSTYPE}/stage1-tools-bin/opt-dist local ${_pgo_opts[@]} -- \
      python x.py install
  else
    DESTDIR="$PWD/build-$MSYSTEM/dest-rust" \
    RUSTFLAGS="${RUSTFLAGS/+crt-static/-crt-static} -C link-arg=-lsecur32" \
      python x.py install --stage 2
  fi

  # Add wasm32-* targets
  if (( _wasm )); then
    DESTDIR="$PWD/build-$MSYSTEM/dest-wasm" \
      python x.py install \
        --stage 1 \
        --keep-stage 0 \
        --exclude compiler/rustc \
        --config "$PWD"/bootstrap-wasm.toml \
        library/std
    # move wasm32-unknown-emscripten out of the way for splitting
    mkdir -p build-${MSYSTEM}/dest-emscripten${MINGW_PREFIX}/lib/rustlib
    mv build-${MSYSTEM}/dest-wasm${MINGW_PREFIX}/lib/rustlib/wasm32-unknown-emscripten \
      build-${MSYSTEM}/dest-emscripten${MINGW_PREFIX}/lib/rustlib
  fi
  if [[ ${CARCH} != i686 ]]; then
    # move src out of the way for splitting
    mkdir -p build-${MSYSTEM}/dest-src${MINGW_PREFIX}/lib/rustlib
    mv build-${MSYSTEM}/dest-rust${MINGW_PREFIX}/lib/rustlib/src \
      build-${MSYSTEM}/dest-src${MINGW_PREFIX}/lib/rustlib
  fi

  rm -f build-${MSYSTEM}/dest-rust${MINGW_PREFIX}/lib/rustlib/$OSTYPE/lib/self-contained/*
}

check() {
  cd "${_realname}c-${pkgver}-src"
  python x.py test --stage 2 --exclude src/test/debuginfo
}

package_rust() {
  depends=("${MINGW_PACKAGE_PREFIX}-cc"
           "${MINGW_PACKAGE_PREFIX}-libgit2"
           "${MINGW_PACKAGE_PREFIX}-libssh2"
           "${MINGW_PACKAGE_PREFIX}-sqlite3"
           "${MINGW_PACKAGE_PREFIX}-zlib")
  # these dependencies are linked with our LLVM library, which has more features enabled
  if (( _pgo )); then
    depends+=("${MINGW_PACKAGE_PREFIX}-llvm-libs")
  else
    depends+=("${MINGW_PACKAGE_PREFIX}-libxml2"
              "${MINGW_PACKAGE_PREFIX}-zstd")
  fi
  if [[ ${CARCH} != i686 ]]; then
    optdepends=("${MINGW_PACKAGE_PREFIX}-gdb: for rust-gdb script"
                "${MINGW_PACKAGE_PREFIX}-lldb: for rust-lldb script")
  fi
  conflicts=("${MINGW_PACKAGE_PREFIX}-rust-docs")
  replaces=("${MINGW_PACKAGE_PREFIX}-rust-docs")

  cd "${_realname}c-${pkgver}-src/build-${MSYSTEM}"

  cp -a dest-rust/* "${pkgdir}"

  # delete unnecessary files, e.g. components and manifest files only used for the uninstall script
  # and rust-{gdb{,gui},lldb} for i686
  cd "${pkgdir}${MINGW_PREFIX}/lib/rustlib"
  rm components install.log manifest-* rust-installer-version uninstall.sh
  rm "${pkgdir}${MINGW_PREFIX}/etc/target-spec-json-schema.json"
  if [[ ${CARCH} == i686 ]]; then
    rm "${pkgdir}${MINGW_PREFIX}"/bin/rust-{gdb{,gui},lldb}
  fi

  install -d "${pkgdir}${MINGW_PREFIX}/share/bash-completion/completions"
  mv "${pkgdir}${MINGW_PREFIX}/etc/bash_completion.d/cargo" \
     "${pkgdir}${MINGW_PREFIX}/share/bash-completion/completions/cargo"
}

package_rust-wasm() {
  pkgdesc="WebAssembly targets for Rust (mingw-w64)"
  depends=("${MINGW_PACKAGE_PREFIX}-lld"
           "${MINGW_PACKAGE_PREFIX}-rust"
           "${MINGW_PACKAGE_PREFIX}-wasm-component-ld")
  # strip wasm object files manually due to binutils' lack of support
  options=('!strip')

  cd "${_realname}c-${pkgver}-src/build-${MSYSTEM}"

  cp -a dest-wasm/* "${pkgdir}"

  pushd "${pkgdir}${MINGW_PREFIX}"/lib/rustlib
    llvm-strip --strip-debug wasm32{,v1}-*/lib/*.rlib
  popd

  install -Dm644 ../LICENSE-{APACHE,MIT} -t "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}-wasm"

  cd "${pkgdir}${MINGW_PREFIX}/lib/rustlib"
  rm components install.log manifest-* rust-installer-version uninstall.sh
}

package_rust-emscripten() {
  pkgdesc="Emscripten target for Rust (mingw-w64)"
  depends=("${MINGW_PACKAGE_PREFIX}-rust"
           "${MINGW_PACKAGE_PREFIX}-emscripten"
           "${MINGW_PACKAGE_PREFIX}-cc-libs"
           "${MINGW_PACKAGE_PREFIX}-llvm-libs"
           "${MINGW_PACKAGE_PREFIX}-zlib"
           "${MINGW_PACKAGE_PREFIX}-zstd")
  options=('!strip')

  cd "${_realname}c-${pkgver}-src/build-${MSYSTEM}"

  cp -a dest-emscripten/* "${pkgdir}"

  pushd "${pkgdir}${MINGW_PREFIX}"/lib/rustlib
    llvm-strip --strip-debug wasm32-*/lib/*.rlib
  popd

  # manually add self-contained linkers to make emscripten target happy
  mkdir -p "${pkgdir}${MINGW_PREFIX}/lib/rustlib/$OSTYPE/bin/gcc-ld/"
  cp "${MINGW_PREFIX}"/bin/{ld{,64}.lld,lld-link,wasm-ld} \
    "${pkgdir}${MINGW_PREFIX}/lib/rustlib/$OSTYPE/bin/gcc-ld/"

  install -Dm644 ../LICENSE-{APACHE,MIT} -t "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}-emscripten"
}

package_rust-src() {
  pkgdesc='Source code for the Rust standard library (mingw-w64)'
  depends=("${MINGW_PACKAGE_PREFIX}-rust")

  cd "${_realname}c-${pkgver}-src/build-${MSYSTEM}"

  cp -a dest-src/* "${pkgdir}"
  install -Dm644 ../LICENSE-{APACHE,MIT} -t "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}-src"
}

# 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;
