# Maintainer: Maksim Bondarenkov <maksapple2306@gmail.com>

_realname=repgrep
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=0.16.1
pkgrel=1
pkgdesc="An interactive replacer for ripgrep that makes it easy to find and replace across files on the command line (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url='https://github.com/acheronfail/repgrep/'
msys2_references=(
  'purl: pkg:cargo/repgrep'
)
license=('spdx:Apache-2.0 OR MIT OR Unlicense')
depends=("${MINGW_PACKAGE_PREFIX}-ripgrep")
makedepends=("${MINGW_PACKAGE_PREFIX}-rust"
             "${MINGW_PACKAGE_PREFIX}-asciidoctor")
options=('!strip')
source=("https://github.com/acheronfail/repgrep/archive/${pkgver}/${_realname}-${pkgver}.tar.gz"
        "asciidoctor-use-full-path.patch")
sha256sums=('4c948dab58ad38c497502782d34821aceedd6670e407ec2c0f4a5a7ba6e78cc0'
            '045bcd49c03ad51c7cb6dbbb8a120daf9e1a63acf8a85ececf4cd671d2031c07')

prepare() {
  cd "${_realname}-${pkgver}"

  patch -Np1 -i ../asciidoctor-use-full-path.patch
  local _asciidoctor="$(cygpath -am ${MINGW_PREFIX}/bin/asciidoctor)"
  sed -i "s|\"ASCIIDOCTOR\"|\"${_asciidoctor}\"|g" build.rs

  rm rust-toolchain.toml
  cargo fetch --locked --target "$(rustc -vV | sed -n 's/host: //p')"
}

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

  WINAPI_NO_BUNDLED_LIBRARIES=1 \
    cargo build --release --frozen
}

check() {
  cd "${_realname}-${pkgver}"

  WINAPI_NO_BUNDLED_LIBRARIES=1 \
    cargo test --release --frozen
}

package() {
  cd "${_realname}-${pkgver}"

  install -Dm755 target/release/rgr "${pkgdir}${MINGW_PREFIX}/bin/rgr"

  out_dir=$(find target -name repgrep-stamp -print0 | xargs -0 ls -t | head -n1 | xargs dirname)
  install -Dm644 "${out_dir}/rgr.1" -t "${pkgdir}${MINGW_PREFIX}/share/man/man1"

  # upstream just reuse rg completions
  # see https://github.com/acheronfail/repgrep/commit/fae1ed5fe9a464fbc7367e441ccc0a2999a72e70
  echo 'complete -F _rg rgr' |
    install -Dm644 /dev/stdin "${pkgdir}${MINGW_PREFIX}/share/bash-completion/completions/rgr"
  echo 'compdef $_comps[rg] rgr' |
    install -Dm644 /dev/stdin "${pkgdir}${MINGW_PREFIX}/share/zsh/site-functions/_rgr"
  rg --generate complete-fish |
    sed -e 's/-c rg/-c rgr/' |
    install -Dm644 /dev/stdin "${pkgdir}${MINGW_PREFIX}/share/fish/vendor_completions.d/rgr.fish"

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