#!/bin/bash
busted_libs=( cliargs dkjson luassert mediator penlight say system term )
found_libs=()

check_package() {
  pkg=$1
  if dpkg -l "$pkg" | grep -q ^ii ; then
     echo "$pkg installed"
     return 0
  fi

  while read vpkg ; do
    if printf '%s\0' "${found_libs[@]}" | grep -qwz $vpkg ; then
       echo "$pkg => $vpkg already installed"
       return 0
    fi
    if dpkg -l "$vpkg" | grep -q ^ii ; then
       found_libs+=( $vpkg )
       echo "$pkg => $vpkg installed"
       return 0
    fi
  done < <( apt-cache showpkg "${pkg}" | sed -e '1,/^Reverse Provides: *$/ d' -e 's/ .*$//' | sort | uniq )
  return 1
}

check_busted () {
  for lib in "${busted_libs[@]}" ; do
    if ! check_package $lua_version-$lib ; then
      return 1
    fi
  done
  return 0
}

for def in debian/lua*.dh-lua.conf; do
  lua_version=${def%.dh-lua.conf}
  lua_version=${lua_version#debian/}
  if check_busted ; then
    echo "run busted with $lua_version"
    busted --lua=/usr/bin/$lua_version --exclude-tags=manual spec/
  else
    echo "skip busted with $lua_version"
  fi
done
