#!/bin/sh

# Usage: ood-packages [-c|-r] [LOCATION]

# Outputs a list of package names which are out of date in the apt
# repository relative to the source tree.  This script only deals with
# regular Debian package sources, not equivs-built packages or
# debathenify packages.  This scripts assumes gen-packages has been
# run to create the packages file.

# If -c is specified, scans a checkout for current version
# information.  If -r is specified, scans the repository.  -r is the
# default.  Using a checkout is faster but will give the wrong results
# if the checkout is not up to date.  This script is kind of slow
# regardless, due to all of the reprepro invocations.

# If LOCATION is specified, it is used in preference to the canonical
# Athena repository trunk or the canonical source checkout.

set -e

. $(dirname "$0")/debian-versions.sh

die() {
  echo "$@" >&2
  exit 1
}

usage() {
  die "ood-packages [-r|-c] [LOCATION]"
}

type=repos

while getopts cr opt; do
  case "$opt" in
  c)
    type=checkout
    ;;
  r)
    type=repos
    ;;
  \?)
    usage
    ;;
  esac
done

shift $(($OPTIND - 1))
if [ $# -gt 0 ]; then
  loc=$1
elif [ $type = repos ]; then
  loc=svn+ssh://svn.mit.edu/athena/trunk
else
  loc=/afs/dev.mit.edu/source/src-svn
fi

packages=packages

if [ ! -r "$packages" ]; then
    packages=/mit/debathena/packages/packages
fi
if [ ! -r "$packages" ]; then
  echo "Can't read packages file; create with gen-packages." >&2
  exit 1
fi

exec <"$packages"
while read pkg path; do
  # Get the version from the apt repository, checking that it is
  # consistent across all dists.
  lastver=
  for dist in $DEBIAN_CODES; do
    if dareprepro list "${dist}-proposed" "$pkg" | grep -q 'source: '; then
      release=-proposed
    else
      release=''
    fi
    aptver=$(dareprepro list "${dist}${release}" "$pkg" \
          | awk '/source:/ { print $3 }')
    if [ -n "$lastver" -a "x$aptver" != "x$lastver" ]; then
      echo -n "WARNING: Inconsistent versions for $pkg: "
      echo "$lastdist $lastver != $dist $aptver" >&2
    fi
    lastver=$aptver
    lastdist=$dist
  done

  # Get the current version from the checkout or repository.
  if [ $type = repos ]; then
    svn cat $loc/$path/debian/changelog > changelog
    cfile=changelog
  else
    cfile=$loc/$path/debian/changelog
  fi
  curver=$(dpkg-parsechangelog -l$cfile | sed -n 's/Version: //p')

  # Display the package name if the apt repository version does not
  # match the current version.
  if [ "x$aptver" != "x$curver" ]; then
    case "$pkg" in 
      debathena-linerva*)
      ;;
      *)
        echo "$pkg"
      ;;
    esac
  fi
done

if [ $type = repos ]; then
  rm -rf changelog
fi
