#!/bin/sh

OVERVIEW_TMPDIR="tmp-overview"
PLUGINS_TMPDIR="tmp-plugins"
OVERVIEW_LIST="list-overview"
PLUGINS_LIST="list-plugins"

test ! -d $OVERVIEW_TMPDIR && mkdir $OVERVIEW_TMPDIR
test ! -d $PLUGINS_TMPDIR && mkdir $PLUGINS_TMPDIR

echo "Generating list of all overview pages..."
for i in `seq 1 93`; do
	echo "http://wordpress.org/extend/plugins/browse/popular/page/$i"
done > $OVERVIEW_LIST

echo "Downloading all overview pages..."
cd $OVERVIEW_TMPDIR
wget -i ../$OVERVIEW_LIST

echo "Generating list of all plugin pages..."
#grep -i -A1 "plugin-block" * | grep h3 | sed 's/.*href="\([^"]*\)">\([^<]*\).*/<plugin name="\2" href="\1"\/>/'
grep -i -A1 "plugin-block" * | grep h3 | sed 's/.*href="\([^"]*\).*/\1/' | sort | uniq | grep ^http > ../$PLUGINS_LIST

echo "Downloading all plugin pages..."
cd ../$PLUGINS_TMPDIR
wget -i ../$PLUGINS_LIST

echo "Generating XML file for plugins..."
(
echo "<?xml version='1.0'?>"
echo "<plugins>"
for i in `ls`; do
	NAME=`grep -B2 "plugin-info" $i | head -1 | cut -f2 -d'>' | cut -f1 -d'<'`
	test "x$NAME" = "x" && continue
	HREF=`grep "Description" $i | sed 's/.*href=\"\([^"]*\).*/\1/'`
	DOWNLOAD=`grep "button btn-l" $i | sed "s/.*href=\'\([^\']*\).*/\1/"`
	VERSION=`grep -i "<strong>Version:</strong>" $i | sed 's/.*Version:<\/strong> \([^<]*\)<.*/\1/'`
	test "x$VERSION" = "x" && VERSION="unknown"
	echo "<plugin name=\"$NAME\" version=\"$VERSION\" download=\"$DOWNLOAD\" href=\"$HREF\"/>"
done
echo "</plugins>"
) | sed 's/&\([^;]*\);/\1/' > ../plugins-`date +%Y-%m-%d`.xml
