#!/bin/sh

list() {
  find /usr/ports -name 'pkg-descr' -depth 3 | while read pkgdescr; do
    portdir=$(dirname "${pkgdescr}")
    makefile="${portdir}/Makefile"
    output=$(grep -o "devel/py-pytest" "${makefile}")
    if [ ! -z "${output}" ]; then
      echo "${portdir}"
    fi
  done | sort
}

test() {
  if [ -z "${1}" -o ]; then 
    echo "Usage: ${0} test <dir>" >&2
    exit 1
  fi
  if [ ! -d "${1}" ]; then
    echo "${1} is not directory" >&2
    exit 1
  fi
  if [ ! -f "${1}/list.txt" ]; then
    echo "The directory ${1} does not contain list.txt" >&2
    exit 1
  fi
  slog="${1}/success.log"
  flog="${1}/failed.log"
  touch "${slog}"
  echo -n "" >"${flog}"
  cat "${1}/list.txt" | while read portdir; do
    success=$(grep -o "^${portdir}\$" "${slog}")
    if [ -z "${success}" ]; then
      make -C "${portdir}" -DBATCH test
      ret=$?
      if [ "${ret}" = "0" ]; then
        echo "${portdir}" >>"${slog}"
      else
        echo "${portdir}" >>"${flog}"
      fi
      make -C "${portdir}" clean
    else
      echo "Skipping ${portdir}"
    fi
  done
}

$@
