#!/usr/bin/python
"""

Fetch a random Astronomy Photo of the Day from NASA to the GNOME desktop and
set the desktop background. Saves the explanation page to the desktop just in
case you get curious. Runs nicely with the GNOME desktop style set to "Scaled"
and the gnome-terminal background set to about 50-70% transparent.

Can be run in cron as:

# m h  dom mon dow   command
*/5 *  *   *   *     python ~/apodbg.py 2>/dev/null

"""

title = "Astronomy Photo of the Day"
base = "http://apod.nasa.gov/apod/"

import datetime, random, urllib, re, os

start = datetime.datetime(1995, 6, 20)
delta = datetime.datetime.now() - start
someday = start + datetime.timedelta(random.randrange(delta.days),0,0)
html = base + "ap" + someday.strftime("%y%m%d") + ".html"
content = urllib.urlopen(html).read()

desktop = os.environ["HOME"] + "/Desktop/"
note = open(desktop + title + ".html", "w")
note.write('<base href="%s">\n' % base)
note.write(content)
note.close()

target = desktop + title + ".png"
img = re.findall(r'<img\s+src="(.*?)"', content, re.IGNORECASE)[0]
img = urllib.basejoin(base, img)
urllib.urlretrieve(img, target)

os.system(
  "gconftool -t str -s /desktop/gnome/background/picture_filename \"%s\"" %
  target)
