#!/bin/bash
TOPIC=`echo $QUERY_STRING | sed "s/\([0-9]\+\)\.xml/\1/g"`

if [ $TOPIC = '' ]; then
	echo 'Content-type: text/html'
	echo ''
	echo '<html>Een topic is wel een vereiste...</html>'
else
	curl --use-ascii -s -b /tmp/fok/fok.cookie -c /tmp/fok/fok.cookie http://forum.fok.nl/topic/$TOPIC | iconv -f iso-8859-15 -t utf-8 > /tmp/fok/$TOPIC
	TITLE=`grep "<title>" /tmp/fok/$TOPIC | sed "s/^<title>.*\/ \(.*\)<\/title>$/\1/g"`
	grep "msg(" /tmp/fok/$TOPIC > /tmp/fok/$TOPIC-msg
	rm /tmp/fok/$TOPIC
	echo "<?xml version='1.0' encoding='UTF-8'?>" > /tmp/fok/build-$TOPIC
	echo "<?xml-stylesheet type='text/xsl' href='kinkrforum.xsl' ?>" >> /tmp/fok/build-$TOPIC
	echo "<topic id='$TOPIC' title='$TITLE'>" >> /tmp/fok/build-$TOPIC
	echo "<users>" >> /tmp/fok/build-$TOPIC
	msg(57917215,1207677763,1143656,0,193141,'Gercos','dinsdag 8 april 2008 @ 20:02','traagheid heb ik niet echt last van maar wel geregeld  die foutmeldingen.','','','','','','','','','','',0,'0','0','');

	cat /tmp/fok/$TOPIC-msg | sed "s/^msg([0-9]\+,[0-9]\+,[0-9]\+,[0-9]\+,\([0-9]\+\),'\(.*\)','[a-z]\+ [0-9]\+ [a-z]\+ [0-9]\+ @ [0-9]\+:[0-9]\+','.*','\(.*\)','\(.*\)','\(\|http:\/\/i.fok.nl\/usericons\/[0-9]\+\/\(.*\)\)','.*','.*','.*','\(.*\)','\(.*\)','[0-9]*','.*',[0-9],'[0-9]','[0-9]','.*');$/<user id='\1' username='\2' subtitle='\3' type='\7' icon='\6'>\4<\/user>/g" | sed 's/\\\"/"/g' | sed "s/\\\'/'/g" | sort -u >> /tmp/fok/build-$TOPIC
	
	cat /tmp/fok/$TOPIC-msg | sed "s/^msg([0-9]\+,[0-9]\+,[0-9]\+,[0-9]\+,\([0-9]\+\),'\(.*\)','[a-z]\+ [0-9]\+ [a-z]\+ [0-9]\+ @ [0-9]\+:[0-9]\+','.*','\(.*\)','\(.*\)','\(\|http:\/\/i.fok.nl\/usericons\/[0-9]\+\/\(.*\)\)','.*','.*','.*','\(.*\)','\(.*\)','[0-9]*','.*',[0-9],'[0-9]','[0-9]','.*');$/<user id='\1' username='\2' subtitle='\3' type='\7' icon='\6'>\4<\/user>/g" | sed 's/\\\"/"/g' | sed "s/\\\'/'/g" | sort -u >> /tmp/fok/build-$TOPIC


	echo "</users>" >> /tmp/fok/build-$TOPIC
	echo "<replies>" >> /tmp/fok/build-$TOPIC
	cat /tmp/fok/$TOPIC-msg | sed "s/^msg(\([0-9]\+\),\([0-9]\+\),[0-9]\+,\([0-9]\+\),\([0-9]\+\),'.*','[a-z]\+ [0-9]\+ [a-z]\+ [0-9]\+ @ [0-9]\+:[0-9]\+','\(.*\)','.*','.*','.*','.*','.*','.*','.*','.*','[0-9]*','.*',[0-9],'[0-9]','[0-9]','.*');$/<reply id='\1' date='\2' pi='\3' userid='\4' xmlns='http:\/\/www.w3.org\/1999\/xhtml'>\5<\/reply>/g" |  sed 's/\\\"/"/g' | sed "s/\\\'/'/g" >> /tmp/fok/build-$TOPIC
	echo "</replies>" >> /tmp/fok/build-$TOPIC
	echo "</topic>" >> /tmp/fok/build-$TOPIC
	rm /tmp/fok/$TOPIC-msg
	cat /tmp/fok/build-$TOPIC | tr "\n" "\t" | perl htmlbagger.pl | sed "s/&\([^#]\)/\&amp;\1/g" | tr "\t" "\n" > /var/www/contrib/fok/$TOPIC.xml
	rm /tmp/fok/build-$TOPIC

	echo "Location: http://fok.kinkrsoftware.nl/$TOPIC.xml"
	echo ''
fi

