#!/bin/sh

set -e

# Exit if refresh_blends is null in umegaya.conf.
[ $(grep ^refresh_blends /etc/umegaya/umegaya.conf |
  sed -r 's/refresh_blends:\s+//') = 0 ] && exit 0

# Exit if curl, debcheckout, umegaya-adm, umegaya-guess-url or svn are not installed.
# Exit code is zero as this script is intended as a cron job.
[ -x /usr/bin/curl ]              || exit 0
[ -x /usr/bin/debcheckout ]       || exit 0
[ -x /usr/bin/umegaya-adm ]       || exit 0
[ -x /usr/bin/umegaya-guess-url ] || exit 0
[ -x /usr/bin/svn ]               || exit 0

# Start with debichem med and science, but later let's fetch all the
# names from $(svn ls svn://svn.debian.org/blends/projects/)
BLENDS='debichem debian-med debian-science'

#set -x
for BLEND in $BLENDS
do
  BLEND_URL=$(debcheckout -d $BLEND | grep url | cut -f2)

  # Learn VCS URL for packages not yet in Debian.
  for TASK in $(svn ls $BLEND_URL/tasks)
  do
    for VCS_URL in $(svn cat $BLEND_URL/tasks/$TASK | grep 'Vcs-[SG]' | cut -f2 -d' ')
    do
      PACKAGE=$(umegaya-guess-url $VCS_URL | cut -f1)
      [ $PACKAGE ] &&
      umegaya-adm -p $PACKAGE -k YAML-URL -v $VCS_URL
    done
  done

  # Refresh Umegaya for each package.
  PACKAGES=$(
    svn cat $BLEND_URL/debian/control |
    grep -e ^Recommends -e ^Suggests |
    sed -e 's/,//g' -e 's/|//g' -e 's/Recommends://g' -e 's/Suggests://g' )
  for PACKAGE in $PACKAGES 
  do
    SOURCE=$(apt-cache showsrc $PACKAGE 2> /dev/null | grep Package -m1 | awk '{print $2}')
    if [ "$SOURCE" != "" ] ; then
      # make sure a failed ping will not interupt script
      curl --silent "http://localhost/umegaya/$SOURCE/ping" || true
      if [ $? != 0 ] ; then
        echo "$0: Problem pinging $SOURCE ($?)"
      fi
    fi
  done
done

# create downloadable archive of the fetched files
STOREFILES=`grep ^store_files /etc/umegaya/umegaya.conf | sed -r 's/store_files:\s+//'`
TARGETARCHIVE=`grep ^archive_for_bibref_gatherer /etc/umegaya/umegaya.conf | sed -r 's/archive_for_bibref_gatherer:\s+//'`

if [ $TARGETARCHIVE != "" -a $STOREFILES != "" ] ; then
  STOREDIR=`dirname $STOREFILES`
  if [ -d $STOREDIR ] ; then
    cd $STOREDIR
    BASESTOREDIR=`basename $STOREFILES`
    if [ -d $BASESTOREDIR ] ; then
      tmpignorezerolengthfiles=`mktemp`
      find packages-metadata -size 0 >> $tmpignorezerolengthfiles
      tar --exclude-vcs --exclude-from $tmpignorezerolengthfiles -cjf $TARGETARCHIVE $BASESTOREDIR
      rm -f $tmpignorezerolengthfiles
    fi
  fi
fi

