#!/bin/bash
#                      /usr/local/bin/silverd
# http://crystalfaeries.net/posix/bin/silverd
# celeste:crystalfaery SILVERD 2017-07-11 19:41:04+00:00
# silverd is a daemon to keep us up-to-date on the price of silver in U$FRNs
# /etc/cron.d/silver:
# @reboot root    /usr/local/bin/silverd >> /var/log/silver.log 2>&1

# User selected parameters:
silver_file=/usr/local/share/ag/kitco.txt	# Where do we store the latest price data?
silver_log=/usr/local/share/ag/silverlog.txt	# where do we store the aggregate silver log?
cron_log=/var/log/silver.log		# where do we store the cronjob's silver log?
let max_sleep=3600			# Maximum time between polls is 60 minutes
let min_sleep=900			# Minimum time between polls is 15 minutes
let sleep=$min_sleep			# Poll soon after computer boot-up
while [ -e $silver_file ]
do
    old_price="`cat $silver_file`"
	price="`wget -q -O - http://www.kitco.com/texten/texten.html | lynx -dump -stdin | grep Silver | head -n 1 | sed 's/         / / ; s/       / /'  | sed 's/     / / ; s/   / / ; s/  / / ; s/ Silver // ; s/ .*$//'`"
    if [ "$price" != "" ]
    then
	echo "$price" > "$silver_file"
	if [ "$price" == "$old_price" ]
	then
		let sleep=$sleep+$sleep
		if [[ $sleep -gt $max_sleep ]]
			then let sleep=$max_sleep
		fi
		touch $silver_file	# update the time reported by our cgi
	else
		let sleep=$sleep/2
		if [[ $sleep -lt  $min_sleep ]]
			then let sleep=$min_sleep
		fi
		echo "`/usr/local/bin/now` KitCoAg: $price" >> $silver_log
	fi
    else
	let sleep=$sleep+$sleep
    fi
	sleep $sleep
done				# hope you launched from a terminal in order to authorize our first run:
sudo touch			$cron_log $silver_log $silver_file #create		missing file
sudo chmod 664			$cron_log $silver_log $silver_file #set permissions:  missing file
sudo chown www-data:www-data	$cron_log $silver_log $silver_file #set ownership of	missing file


syntax highlighted by Code2HTML, v. 0.9.1