#!/bin/bash

cd ..

EBUILDS=$(find . -name \*.ebuild | grep -v _darcs | sed -e "s/\.\\///" | sort)

RST=projects/GHC-6.6-failures.rst

PORTAGE=/usr/portage

YELLOW="\033[33m"
RED="\033[31m"
NORMAL="\033[0m"

if [[ "$1" == "--help" ]]; then
  echo usage: $0
  echo [123] package
  echo 1. X means the package is present in $RST, otherwise not present
  echo 2.   empty means the package is only present in the overlay
  echo 2. B means the package is present both in the overlay and in $PORTAGE
  echo 2. P means the package is only present in $PORTAGE, not in the ovelay
  echo 3. D means the package in the overlay is different from the $PORTAGE version
  exit 0
fi

# check packages that are in the overlay
for EBUILD in ${EBUILDS}; do
  PKG=$(echo "${EBUILD}" | sed -e s/.ebuild// | cut -d '/' -f 1,3)
  echo -n "["
  grep --quiet "^${PKG}" "${RST}"
  if [[ $? -eq 0 ]]; then
    # present in the failure list
    echo -n "X"
  else
    echo -n " "
  fi
  if [[ -f "${PORTAGE}/${EBUILD}" ]]; then
    # exists both in the overlay and portage
    echo -n "B"

    #ignore comment lines
    T1=$( mktemp )
    T2=$( mktemp )

    cat "${EBUILD}" > $T1
    cat "${PORTAGE}/${EBUILD}" > $T2
    
    sed -e "s/#.*//" -i "${T1}"
    sed -e "s/#.*//" -i "${T2}"

    diff -q "${T1}" "${T2}" > /dev/null
    if [[ $? -eq 1 ]]; then
      # file in overlay and portage differs
      echo -n -e "${RED}D${NORMAL}"
    else
      echo -n " "
    fi
    rm -f $T1
    rm -f $T2
   else
    echo -n "  "
  fi
  echo "] ${PKG}"
done


# find packages in cvs that aren't in the overlay
NAMES=$( echo "${EBUILDS}" | cut -d '/' -f 1,2 | uniq | sort )

for NAME in ${NAMES}; do
  if [[ ! -d "${PORTAGE}/${NAME}" ]]; then
    # the packages does not exist in portage
    continue
  fi

  # find packages in portage 
  for CVSNAME in $( find "${PORTAGE}/${NAME}" -name "*.ebuild" ); do
    SHORT_CVSNAME=$( echo "$CVSNAME" | sed -e "s|${PORTAGE}/||" )
    if [[ -f "${SHORT_CVSNAME}" ]]; then
      # file alreay exist in overlay, which means we've already tested it
      continue
    fi
    PKG=$( echo "${SHORT_CVSNAME}" | sed -e s/.ebuild// | cut -d '/' -f 1,3 )
    echo -n "["
    grep --quiet "^${PKG}" "${RST}"
    if [[ $? -eq 0 ]]; then
      # package present in failure list
      echo -n "X"
    else
      echo -n " "
    fi
    echo "P ] ${PKG}"
  done
done

# vim: tw=76 ts=2 :
