#!/bin/bash
# picngs: Download today's picture from National Geographics website
# Michael.ZhanShi@Gmail.com

# arg1: datefmt example: 20080713
# arg2: picdir example: /Users/yourname/Pictures

export LC_ALL=C

BADDATE=66
WEBFAILURE=67
SEDFAILURE=68

pntmp=$(basename "$0")_$$

picdir=${2:-.}

cd /tmp

if [ $# -eq 0 ]
then
    mfdate=$(date +%Y.%m.%d)
    wget -q "http://lava.nationalgeographic.com/pod/" -O $pntmp
else
    if date -d "$1" +%Y-%m-%d 2>/dev/null
    then
        mfdate=$(date -d $1 +%Y.%m.%d)
        wget -q "http://photography.nationalgeographic.com/ngs_pod_ext/searchPOD.jsp?day=$(date -d $1 +%d)&month=$(date -d $1 +%m)&year=$(date -d $1 +%Y)" -O $pntmp
	if [ $? -ne 0 ]
	then
	    echo "Error in finding picture." >&2
	    exit $WEBFAILURE
	fi
    else
        echo "Unknown date format." >&2
        exit $BADDATE
    fi
fi

papername=$(sed 's@ class="[^"]*"@@g' $pntmp | grep '/wallpaper/' | cut -d'=' -f2 | cut -d'"' -f2)

picname=$mfdate-$(sed -n '/<title>/s/.*<title>\(.*\)<\/title>.*/\1/p' $pntmp | sed 's/\(.*\), Photo of the Day.*/\1/;s/['"'"',"]//g;s/ \+$//;s/ /_/g;s/\//_/g;'"s/&#039/'/g" | tr '[:upper:]' '[:lower:]')

wget -q "http://photography.nationalgeographic.com""$papername" -O $pntmp

findname=$(grep 'widescreen' $pntmp | cut -d'=' -f2 | cut -d'"' -f2)
# findname=$(sed -n '1,/slide/d;/img/{p;q}' $pntmp | sed 's/.*src="\([^"]*\)".*/\1/' | sed 's/-ga\./-xl\./')

if [ -z "$findname" ]
then
    echo "No picture found." >&2
    exit $SEDFAILURE
fi

wget -q -c "http://photography.nationalgeographic.com""$findname" -O "$picdir/$picname.jpg"

if [ $? -ne 0 ]
then
    echo "Error in downloading picture." >&2
    exit $WEBFAILURE
fi

echo "Done."

# uncomment the next row if you love Growl fro Mac OS
# growlnotify --image "$picdir/$picname.jpg" -m "National Geographic Picture of the Day $mfdate downloaded."

exit 0
