#!/bin/bash

# Upstream watcher to be executed from cron

if [ "$1" = "" ]; then
	DIRS="."
else
	DIRS="$*"
fi

# Process a single watch item
# $1 = FTP Site
# $2 = Directory on site
# $3 = Pattern to match
# $4 = Last Version we have (or debian for the current debian version)
# $5 = Actions to take on successful retrieval
function watch()
{
#	echo "Entering watch with $*"
	MATCHING=`echo "$3" | sed -e 's/\./\\\./g' -e 's/?/./g' -e 's/\*/.*/g'`
#	echo "Matching=$MATCHING"
	NFILE=`echo "ls $3" | ncftp $1:$2/ 2>&1 | grep "^$MATCHING" | sort | tail -1`
	# See if there is a new version
	X="$NFILE"
	if [ "$X" ]; then
		# Figure out the type of archive
		case "$X" in
		*.tar.gz)	X=`expr "$X" : "\(.*\).tar.gz"`
			;;
		*.tgz)		X=`expr "$X" : "\(.*\).tgz"`
			;;
		*.tar)		X=`expr "$X" : "\(.*\).tar"`
			;;
		*.zip)		X=`expr "$X" : "\(.*\).zip"`
			;;
		*)	echo "Warning: Unknown Archive type $X"
			;;
		esac

		NVER="`expr "$X" : "[a-zA-Z-]*\([0-9]*\.[0-9\.]*\)"`"
		OURVER="$4";
		if [ "$4" = "debian" ]; then
			OURVER="$UVERSION"
		fi
		echo -n "Version on FTP Site is $NVER. Package is $OURVER"
		if [ "$NVER" '=' "$OURVER" ]; then
			echo " => Package is up to date"
			return
		fi
		if expr "$OURVER" '>' "$NVER"; then
			echo " => FTP site does not have current version"
			return
		fi
		if [ -f ../$NFILE ]; then
			echo " => $NFILE already in package directory"
			return
		fi
		echo " => Newer Release available"
		echo "-- Downloading updated Package $NFILE"
		# Download newer package
		(cd ..;ncftp $1:$2/$NFILE)
		# Do whatever the user wishes to do
		if [ "$5" ]; then
			echo "-- Executing user specified script $5 $NFILE $OURVER $NVER"
			$5 ../$NFILE $NVER
		fi
	else
		echo "No match on site $1 pattern $3"
	fi
}

function process_watchfile()
{
	read X
	while [ "$X" ]; do
		watch $X
		read X
	done
}

ODIR=`pwd`
echo "-- Scanning for watchfiles in $DIRS"
for i in `find $DIRS -name "debian" 2>/dev/null`; do
        DIR=`expr "$i" : "\(.*\)/debian"`
        cd $DIR
	if [ -f debian/watch ]; then
		echo "-- Found watchfile in $DIR"
		# Figure out package info we need
		LINE=`head -1 debian/changelog`
		PACKAGE=`expr "$LINE" : '\(.*\) (.*)'`
		VERSION=`expr "$LINE" : '.* (\(.*\))'`
		UVERSION=`expr "$VERSION" : '\(.*\)-[0-9]*'`
		sed -e '/^#/d' -e '/^$/d' <debian/watch | process_watchfile
	fi
	cd $ODIR
done
echo "-- Scan finished"
