#!/usr/bin/env python

import random
import os
from subprocess import call
from sys import argv

GNOME_2 = False
DIR = '/usr/share/backgrounds'


def main():
    full_filename = ''
    if len(argv) > 1 and argv[1]:
        full_filename = os.path.join(DIR, argv[1])
    else:
        bg_list = os.listdir(DIR)
        background_selected = False
        while not background_selected:
            for value in range(1, 10):
                random.shuffle(bg_list)
            background_image = bg_list.pop()
            print background_image
            if os.path.isfile(os.path.join(DIR, background_image)):
                background_selected = True
        full_filename = os.path.join(DIR, background_image)

    if (GNOME_2):
        call([
            "gconftool-2",
            "--type",
            "string",
            "--set",
            "/desktop/gnome/background/picture_options",
            "stretched"])
        call([
            "gconftool-2",
            "--type",
            "string",
            "--set",
            "/desktop/gnome/background/picture_filename",
            full_filename])
    else:
        call([
            "gsettings",
            "set",
            "org.gnome.desktop.background",
            "picture-uri",
            "file://" + full_filename])
        call([
            "gsettings",
            "set",
            "org.gnome.desktop.background",
            "picture-options",
            'stretched'])
if __name__ == '__main__':
    main()
