# Maintainer: Luke T. Shumaker <lukeshu@parabola.nu>
# Maintainer (arch): David Runge <dvzrv@archlinux.org>
# Maintainer (arch): Andreas 'Segaja' Schleifer <segaja at archlinux dot org>

# Parabola changes and rationale:
#  - generator.c contains non-free code from CVTUTF
#    https://labs.parabola.nu/issues/674
#    https://bugs.ruby-lang.org/issues/11844
#    https://github.com/flori/json/issues/277

_name=json
pkgname="ruby-json"
pkgver=2.7.1
pkgrel=1
pkgdesc="JSON implementation for Ruby"
arch=(x86_64)
url="https://github.com/flori/json"
license=(Ruby)
depends=(
  glibc
  ruby
)
makedepends=(
  ragel
  ruby-rake
  ruby-rdoc
)
checkdepends=(
  ruby-test-unit
  ruby-test-unit-ruby-core
)
source=($url/archive/v$pkgver/$pkgname-$pkgver.tar.gz)
sha512sums=('ce0a1399f0974e3919e85af9aa50e982a5e1adff7312f716033f6a19ce7044b046e037f19fcf43adaeff402c882bd0a3b045e93c245287a7f947754125eb39c6')
b2sums=('f1339558107ee1f4b9a54b63d601c9c4a78ed1a4cc148c3c57d963d5536a1b8ced66dd7cd4b7ea9bc2c5ee5fcb3801c028671884484e16ea7d57d0a49e16f317')

# Parabola: Mundane packaging considerations.
arch+=(armv7h i686)
pkgrel+=.parabola1
makedepends+=(rubygems)

# Parabola: Replace the CVTUTF code with a free implementation.
# https://github.com/flori/json/pull/567
_commit=6e75be64c896e093075ec99bf94a3f5fc576c283
source=("ruby-json-${_commit}.tar.gz::https://github.com/parabola-gnulinuxlibre/ruby-json/archive/${_commit}.tar.gz")

prepare() {
  mv "ruby-json-${_commit}" "$_name-$pkgver" # Parabola
  cd $_name-$pkgver

  # update gemspec/Gemfile to allow newer version of the dependencies
  sed -i -e 's|~>|>=|g' $_name.gemspec
}

build() {
  local gemdir="$(gem env gemdir)"
  local gem_install_options=(
    --local
    --verbose
    --ignore-dependencies
    --no-user-install
    --install-dir tmp_install/$gemdir
    --bindir tmp_install/usr/bin
    $_name-$pkgver.gem
  )
  local unrepro_files=(
    tmp_install/$gemdir/cache/
    tmp_install/$gemdir/gems/$_name-$pkgver/vendor/
    tmp_install/$gemdir/doc/$_name-$pkgver/ri/ext/
  )

  cd $_name-$pkgver

  gem build $_name.gemspec
  gem install "${gem_install_options[@]}"

  # remove unrepreducible files
  rm -frv "${unrepro_files[@]}"

  find tmp_install/$gemdir/gems/ \
    -type f \
    \( \
      -iname "*.o" -o \
      -iname "*.c" -o \
      -iname "*.so" -o \
      -iname "*.time" -o \
      -iname "gem.build_complete" -o \
      -iname "Makefile" \
    \) \
    -delete

  find tmp_install/$gemdir/extensions/ \
    -type f \
    \( \
      -iname "mkmf.log" -o \
      -iname "gem_make.out" \
    \) \
    -delete
}

check() {
  local gemdir="$(gem env gemdir)"

  cd $_name-$pkgver

  #GEM_HOME="tmp_install/$gemdir" rake test # Parabola: bootstrapping problem, idk
}

package() {
  cd $_name-$pkgver

  mv -v tmp_install/* "$pkgdir/"

  install -vDm 0644 LICENSE -t "$pkgdir/usr/share/licenses/$pkgname/"
  install -vDm 0644 ./*.md -t "$pkgdir/usr/share/doc/$pkgname/"
}
