#!/bin/bash

#Set IO redirection to overwrite
set -o noclobber ON

#Get the home dir
path=$(cd ${0%/*} && echo $PWD/${0##*/})
home=$(dirname "$(dirname "$path")")

cd "$home"

#Set Variables

export sqlHost="mysql.internal"
export sqlPort=3306
export sqlDB="DATABASE"
export sqlUser="USERNAME"
export sqlPass="PASSWORD"

export baseURL=http://www.redbrick.dcu.ie/~gleesog4/rss/feeds
export proxy=proxy.dcu.ie:3128

export requestTimeout=2000
export feedsDir="$home/feeds"
export MAX_NUM_OF_ITEMS=25
export articleStaleTime=1d
export delay_NORM=[45m,3h,12h,1d,100d]
export delay_UPDATE=[30m,1h,2h,12h,1d,100d]
export delay_ERROR=[15m,30m,1h,3h,6h,8h,14h,1d,2d,100d]

export CLASSPATH=$CLASSPATH:app/lib/htmlparser.jar:app/lib/feedparser.jar:app/lib/mysql.jar:app/lib/urlutil.jar:app/bin



#Check If An Instance Is Already Running
if [ -f Err.tmp.txt ]; then

	let "diff = $(date +%s) - $(date -r Err.tmp.txt +%s)"
	let "totalSec = 60 * 13"	#13 Mins

	if [ $diff -gt $totalSec ]; then

		date >> Err1.txt
		echo Killing Old Instance >> Err1.txt
		killall -9 java >> Err1.txt
		rm -f Err.tmp.txt
		sleep 1m
	else
		exit	#The Script May Still Be Ligitimitly Running
	fi
fi

#Set Log File Size Limit
if [ -f Log1.txt ] && [ $(cksum Log1.txt | nawk '{print $2}') -gt 500000 ]; then
	mv -f Log1.txt Log2.txt
fi

echo ========================================================== >> ./Log1.txt
date  >> ./Log1.txt

#Run Scraper
{ java RssExpander 2>&1 >&3 | tee Err.tmp.txt >&3; } 3>> ./Log1.txt

#Set Permmisions And Copy index.cgi
IFS=$'\n'

chmod 711 "$home"

cd "$home/sh"

if [ ! -f index.cgi ] && [ -f index.cgi_ ]; then
	mv -f index.cgi_ index.cgi
fi

cd "$home"

find ./* -type d -exec chmod 700 "{}" \;
find ./* -type f -exec chmod 600 "{}" \;

mkdir -p feeds
find feeds -type d -exec chmod 755 "{}" \;
for i in `find feeds -name "index.rss" -type f`; do cp -u sh/index.cgi ${i%/*}; done 
find feeds -name "index.rss" -type f -exec chmod 644 "{}" \;
find feeds -name "index.cgi" -type f -exec chmod 700 "{}" \;

if [ -d tmp ]; then 
	find tmp -maxdepth 1 -type d -exec chmod 711 "{}" \;
	find tmp -name "index.rss" -type f -exec chmod 644 "{}" \;
fi

find . -name "*.sh" -type f -exec chmod 700 "{}" \;

#End Log Files
date  >> ./Log1.txt
if [ -f Err.tmp.txt ] && [ $(cksum Err.tmp.txt | nawk '{print $2}') -gt 0 ]; then
		
	if [ -f Err1.txt ] && [ $(cksum Err1.txt | nawk '{print $2}') -gt 200000 ]; then
		mv -f Err1.txt Err2.txt
	fi	
	echo ========================================================== >> ./Err1.txt
	date >> Err1.txt
	cat Err.tmp.txt >> Err1.txt
fi

#Cleanup Remove files
rm -f hs_err_pid*.log
rm -f Err.tmp.txt