#!/bin/bash

set -o errexit
set -o errtrace
set -o pipefail
set -o nounset

readonly progpath="$(realpath "$0")"
readonly progname="$(basename "$progpath")"
readonly progdir="$(dirname "$progpath")"
if [ -d "pkg/${MINGW_PACKAGE_PREFIX}-ruby" ]; then
    readonly _pkgdir="pkg/${MINGW_PACKAGE_PREFIX}-ruby${MINGW_PREFIX}/"
else
    readonly _pkgdir="pkg/${MINGW_PACKAGE_PREFIX}-ruby${MINGW_PREFIX}/"
    echo "${_pkgdir} does not exist. Build the package before running this script."
    exit
fi

ruby_default() {
  for f in ${_pkgdir}/lib/ruby/gems/*/specifications/default/*; do
    if [ -f "$f" ]; then
      echo $(basename ${f%.*}) | sed -r 's/(.*)-/\1=/'
    fi
  done
}

ruby_bundled() {
  for f in ${_pkgdir}/lib/ruby/gems/*/cache//*; do
    if [ -f "$f" ]; then
      echo $(basename ${f%.*}) | sed -r 's/(.*)-/\1=/'
    fi
  done
}

usage() {
    echo "   Usage: $progname"
    echo
    echo "   ruby and gawk (mingw-w64) needs to be installed"
    echo
    [[ "${1:-}" =~ ^[0-9]{1,3}$ ]] && exit $1
}

command -v gawk &>/dev/null || usage 1

declare -r tmpfile="$(mktemp)"
ruby_bundled \
| while IFS='' read -r line; do
    echo "$line"
done | sort -f > "$tmpfile"

ruby_default \
| while IFS='' read -r line; do
    echo "$line"
done | sort -f >> "$tmpfile"

mv "PKGBUILD" "PKGBUILD~"

gawk '
/^provides=/ { s = 1 }
s && /)/ {
    s = 0
    print "provides=("
    while ( (getline line < "'"$tmpfile"'") > 0 ) {
        print "    \"${MINGW_PACKAGE_PREFIX}-ruby-" line "\""
    }
    print ")"
    next
}
s { next }
! s { print }
' "PKGBUILD~" > "PKGBUILD"

rm "$tmpfile"

# vim: set ts=4 sw=4 et ai:
