#!/usr/bin/env python

import argparse
import json
import os
import shutil
import subprocess
import tempfile
import urllib

BASE_URL = "http://www.bing.com/"

OSASCRIPT_PATH = "/usr/bin/osascript"
GSETTINGS_PATH = "/usr/bin/gsettings"

SET_SCRIPT = """
tell application "System Events"
    set picture of every desktop to POSIX file "%s"
end tell
"""


class TempDir(object):

    def __init__(self):
        self.pwd = None
        self.path = None

    def __enter__(self):
        self.pwd = os.getcwd()
        self.path = tempfile.mkdtemp()
        os.chdir(self.path)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        os.chdir(self.pwd)
        shutil.rmtree(self.path)


def main():
    parser = argparse.ArgumentParser(description="Download the current bing.com image.")
    parser.add_argument("destination", help="Destination directory.")
    parser.add_argument("--set-desktop-picture", action="store_true", default=False, help="Set the OS X or Ubuntu desktop.")
    options = parser.parse_args()

    response = urllib.urlopen("%s%s" % (BASE_URL, "HPImageArchive.aspx?format=js&n=1&mkt=en-US&idx=0"))
    contents = json.loads(response.read())
    paths = [image["url"] for image in contents["images"]]

    images = []

    destination_dir = os.path.abspath(options.destination)
    if not os.path.isdir(destination_dir):
        exit("Failed. '%s' is not a directory." % (destination_dir))

    for path in paths:
        url = "%s%s" % (BASE_URL, path)
        _, filename = os.path.split(path)
        destination = os.path.join(options.destination, filename)

        if os.path.exists(destination):
            continue

        print "Downloading '%s'..." % (filename)
        with TempDir():
            urllib.urlretrieve(url, filename)
            shutil.move(filename, destination)

        images.append(destination)

    if options.set_desktop_picture and images:
        path = images[0]
        if os.path.exists(OSASCRIPT_PATH):
            subprocess.check_call([OSASCRIPT_PATH, "-e", SET_SCRIPT % path])
        elif os.path.exists(GSETTINGS_PATH):
            subprocess.check_call([GSETTINGS_PATH, "set", "org.gnome.desktop.background", "picture-uri", "file://%s" % (path)])
        else:
            exit("Unable to set desktop.")

    print "Complete. %d new file(s)." % (len(images))

if __name__ == "__main__":
   main()
