#!/bin/bash

function cleanName ()
{
  echo $1 | sed -re 's/([^0-9a-zA-Z])/\\\1/g'
}

cd /home/download/public_html/maps
ls -1 ./*.pk3 | while read name
do
    if ! grep -Eq "$(cleanName "$name")" ../md5.list ; then
        /usr/bin/md5sum "$name" >> ../md5.list 
        files_have_changed=1
    fi
done

if [ $files_have_changed ] ; then
    tmpfile=$(mktemp)
    cat >$tmpfile <<_!_!!__x
<?xml version="1.0"?>
<rss version="2.0">
   <channel>
      <title>MG Map Repository</title>
      <link>http://downloads.mercenariesguild.net/</link>
      <description>Latest maps for tremulous.</description>
      <language>en-gb</language>
      <lastBuildDate>$(date -R)</lastBuildDate>
      <docs>http://blogs.law.harvard.edu/tech/rss</docs>
      <generator>Custom Script</generator>
      <webMaster>downloads@mercenareisguild.net</webMaster>
      <ttl>15</ttl>
_!_!!__x

    tail ../md5.list | while read line;
    do
	md5=$(echo $line | cut -d' ' -f1)
	name=$(echo $line | cut -d' ' -f2 | sed s':^\./::')
    
    cat >>$tmpfile <<_!_!!__x
    <item>
         <title>$name</title>
         <pubDate>$(date -R -d "$(ls -l "$name" | sed -r 's/ +/ /g' | cut -f6,7,8 '-d ')")</pubDate>
         <link>http://downloads.mercenariesguild.net/$name</link>
         <guid>$md5</guid>
    </item>
_!_!!__x

        unset md5
    done
    
    cat >>$tmpfile <<_!_!!__x
   </channel>
</rss>
_!_!!__x

    cp $tmpfile ../rss.xml
    rm $tmpfile

fi
