#!/bin/sh
#
# Gets sunset / sunrise tables from aa.usno.navy.mil
# http://ubuntu.online02.com/node/36
# Run with cron after midnight but before sunrise (4am) to get the times for the day
# http://www.homeautomationhub.com/sites/default/files/suntimes.txt
City="Portland"
State="Oregon"
LatDeg="45"
LatMin="5"
LonDeg="122"
LonMin="7"
Year=$(date +%Y)
Month=$(date +%m)
Day=$(date +%d)
Dst=$(date +%z | sed 's/+0//' | sed 's/00//'| cut -d- -f2)
TempFile=/tmp/suntable$Year+$Dst.htm
SunRiseFile=/tmp/sunrise$Year$Month$Day.txt
SunSetFile=/tmp/sunset$Year$Month$Day.txt
# <input type="text" name="place" id="placeint" maxlength="32" value="(no name given)">
# <select name="type" id="tabtyb">
# <value="0">sunrise/sunset</option><value="1">moonrise/moonset</option>
# <value="2">civil twilight</option><value="3">nautical twilight</option><value="4">astronomical twilight</option>
# <fieldset><legend><b>Longitude:</b></legend>
# <input type="radio" name="xx0" id="east" value="1" id="west" value="-1">
# <input type="text" name="xx1" id="dego" name="xx2" id="mino">
# <fieldset><legend><b>Latitude:</b></legend>
# <input type="radio" name="yy0" id="north" value="1" id="south" value="-1">
# <input type="text" name="yy1" id="dega" name="yy2" id="mina">
# <fieldset><legend><b>Time Zone:</b></legend>
# <input type="radio" name="zz0" id="zeast" value="1" id="zwest" value="-1">
# <input type="text" name="zz1" id="zhour">
# wget http://aa.usno.navy.mil/cgi-bin/aa_pap.pl --post-data="xxy=$YEAR&xxm=$MONTH&xxd=$DAY&st=$STATE&place=$CITY" -O /tmp/suntable.htm
if [ ! -s $TempFile ]; then
wget http://aa.usno.navy.mil/cgi-bin/aa_pap.pl --post-data="type=0&zz0=-1&zz1=$Dst&xx0=-1&xx1=$LonDeg&xx2=$LonMin&yy0=1&yy1=$LatDeg&yy2=$LatMin&ID=AA&FFX=2&xxy=$Year&xxm=$Month&xxd=$Day&st=$State&placeus=$City&ZZZ=END" -O $TempFile
fi
SUNRISE=$(cat $TempFile | grep Sunrise | sed 's/Sunrise //' | sed 's/\.//g' | sed 's/ //g')
SUNSET=$(cat $TempFile | grep Sunset | sed 's/Sunset //' | sed 's/\.//g' | sed 's/ //g')
# SUNRISE=$(cat $TempFile | grep ^$Day | awk -v n=$Month '{print $(n*2)}')
# SUNSET=$(cat $TempFile | grep ^$Day | awk -v n=$Month '{print $(n*2+1)}')
echo Sunrise: $SUNRISE
echo Sunset: $SUNSET
echo $SUNRISE>$SunRiseFile
echo $SUNSET>$SunSetFile
# Run commands at sunrise or sunset
# at -f /path/to/script.sh $SUNRISE
# at -f /path/to/script.sh $SUNSET