#!/bin/bash
mkdir -p "data"
rm data/stat*.php
if [ -f "id.txt" ]
# refresh from id file
then
	while read line; do  
     		i=$line
		wget -T 10 --retry-connrefused --random-wait -U "Mozilla/5.0 (X11; Linux x86_64; rv:10.0.2) Gecko/20100101 Firefox/13" -O "work.html" "http://www.nyaa.eu/?page=torrentinfo&tid=$i"
		grep "does not appear to be in our database" "work.html" -q && rm "work.html"
		if [ -f "work.html" ]; then
			id=$i
			seed=`cat work.html | awk -F "<td" '{print $11}' | awk -F ">" '{print $3}' | awk -F "<" '{print $1}' | sed '/^$/d'`
			leech=`cat work.html | awk -F "<td" '{print $15}' | awk -F ">" '{print $3}' | awk -F "<" '{print $1}' | sed '/^$/d'`
			downloads=`cat work.html | awk -F "<td" '{print $19}' | awk -F ">" '{print $3}' | awk -F "<" '{print $1}' | sed '/^$/d' | head -n1`
			update=`date +'%s'`
			dbfile=`c=$(($i/1000));echo $c`
				if ! [[ "$seed" =~ ^[0-9]+$ ]];then seed="?";fi
				if ! [[ "$leech" =~ ^[0-9]+$ ]];then leech="?";fi
			sed -i '$ d' "data/stat$dbfile.php" #remove last line
			tail -n +2 "data/stat$dbfile.php" > "data/_stat$dbfile.php"; mv "data/_stat$dbfile.php" "data/stat$dbfile.php" #remove first line
			echo "\$tidstat$id = array('se'=>'$seed','le'=>'$leech','dl'=>'$downloads','up'=>'$update');">>"data/stat$dbfile.php"
			sed -i '1i <?php ' "data/stat$dbfile.php" #prepend line
			echo " ?>">>"data/stat$dbfile.php"	
			rm "work.html"
		fi
	done < "id.txt"
else
# refresh from increment
	read -p "(id.txt not found) Latest torrent id on Magnesia ? " lastknown
	i="0"
	while [ $i -le $lastknown ]; do  
		wget -T 10 --retry-connrefused --random-wait -U "Mozilla/5.0 (X11; Linux x86_64; rv:10.0.2) Gecko/20100101 Firefox/13" -O "work.html" "http://www.nyaa.eu/?page=torrentinfo&tid=$i"
		grep "does not appear to be in our database" "work.html" -q && rm "work.html"
		if [ -f "work.html" ]; then
			id=$i
			seed=`cat work.html | awk -F "<td" '{print $11}' | awk -F ">" '{print $3}' | awk -F "<" '{print $1}' | sed '/^$/d'`
			leech=`cat work.html | awk -F "<td" '{print $15}' | awk -F ">" '{print $3}' | awk -F "<" '{print $1}' | sed '/^$/d'`
			downloads=`cat work.html | awk -F "<td" '{print $19}' | awk -F ">" '{print $3}' | awk -F "<" '{print $1}' | sed '/^$/d' | head -n1`
			update=`date +'%s'`
			dbfile=`c=$(($i/1000));echo $c`
				if ! [[ "$seed" =~ ^[0-9]+$ ]];then seed="?";fi
				if ! [[ "$leech" =~ ^[0-9]+$ ]];then leech="?";fi
			sed -i '$ d' "data/stat$dbfile.php" #remove last line
			tail -n +2 "data/stat$dbfile.php" > "data/_stat$dbfile.php"; mv "data/_stat$dbfile.php" "data/stat$dbfile.php" #remove first line
			echo "\$tidstat$id = array('se'=>'$seed','le'=>'$leech','dl'=>'$downloads','up'=>'$update');">>"data/stat$dbfile.php"
			sed -i '1i <?php ' "data/stat$dbfile.php" #prepend line
			echo " ?>">>"data/stat$dbfile.php"	
			rm "work.html"
		fi
	let i=1+$i
	done
fi
echo "Stat refresh finished"
