#!/usr/bin/python
#
# Copyright (c) 2004 marduk enterprises <marduk@python.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA..

import random
import gconf
import os
import time

_revision_ = '0.9.1'
_usage_ = '[--desktop] [--nautilus] [--icons]'

desk1_key = '/desktop/gnome/background/primary_color'
desk2_key = '/desktop/gnome/background/secondary_color'
nautilus_key = '/apps/nautilus/preferences/background_color'
icon_key = '/desktop/gnome/interface/icon_theme'

# you should only touch these if you know what you're doing
ORIG_LIGHT_COLOR = '#d9cce6'
ORIG_DARK_COLOR = '#73667f'
RGB = '/usr/X11R6/lib/X11/rgb.txt'

def load_rgb():
    rgb = {}
    for line in open(RGB, 'r').readlines():
        line = line.strip()
        fields = line.split(None,3)
        if len(fields) != 4:
            continue
        try:
            color = tuple([int(i) for i in fields[:3]])
            color_name = fields[3]
            rgb[color_name.lower()] = color
            #print color_name,'=',color
        except ValueError:
            continue
    return rgb

def randcolor(min=0, max=255):
    """Return random (R,G,B) color tuple where values for Red, Green, and Blue
    are between min and max (0 <= n <= 255)"""
    return  (random.randint(min,max), 
        random.randint(min,max), random.randint(min,max))

def make_icon_theme(color=None):
    """ok, now for something really funky.  we're gonna try to create our own
    icon theme on-the-fly :-)"""
    lila_theme = find_lila_theme()
    if not lila_theme:
        print 'Cannot find Lila theme.'
        return None
        
    #get colors for our gradient
    color = color or randcolor() #(128,255)
    light_color = '#%02x%02x%02x' % (min(255, color[0] + 127), min(255, 
        color[1] + 127), min(255, color[2] + 127))
    dark_color = '#%02x%02x%02x' % (max(0, color[0] - 127), max(0, 
        color[1] - 127), max(0, color[2] - 127))
        
    # make copy of ORIG_ICON_THEME
    now = time.time()
    theme = 'random-%s' % now
    theme_dir = '${HOME}/.icons/random-%s' % now
    command = '/bin/cp -ra "%s" "%s"' % (lila_theme, theme_dir)
    os.system(command)
    # now we edit the copy...
    # inline shell scripting (i'm bad)
    command = """for i in `find %s -name '*.svg' -print`; do
        cp $i ${HOME}/.random.svg
        sed -e 's/%s/%s/' -e 's/%s/%s/' ${HOME}/.random.svg > $i
        done
    """ % (theme_dir, ORIG_LIGHT_COLOR, light_color, ORIG_DARK_COLOR, 
        dark_color)
    os.system(command)
    return theme

def set_desktop(conf, color=None):
    """Colors are rgb triplets"""
    
    color = color or randcolor()
    #color2 = color2 or randcolor()
    light_color = '#%02x%02x%02x' % (min(255, color[0] + 64), min(255, 
        color[1] + 64), min(255, color[2] + 64))
    dark_color = '#%02x%02x%02x' % (max(0, color[0] - 64), max(0, 
        color[1] - 64), max(0, color[2] - 64))
    #color2 = (255 - color1[0], 255 - color1[1], 255 - color1[2])
    conf.set_string(desk1_key, dark_color)
    conf.set_string(desk2_key, light_color)
    
def set_nautilus(conf, color=None):
    color = color or randcolor()
    conf.set_string(nautilus_key, '#%02x%02x%02x' % color)

def set_icons(conf, color=None):
    current_theme = conf.get(icon_key).get_string()
    theme = make_icon_theme(color) or current_theme
    conf.set_string(icon_key, theme)
            
    # remove old theme
    if current_theme[:7] == 'random-':
        command = 'rm -rf "${HOME}/.icons/%s"' % current_theme
        os.system(command)
        
def find_lila_theme():
    """return path of Lila theme or None if not found"""
    paths = ['%s/.icons/Lila' % os.environ['HOME'], 
        '/usr/local/share/icons/Lila', '/usr/share/icons/Lila' ]
    
    for path in paths:
        if os.path.isdir(path):
            return path
    return None
    
def main(argv=[None]):
    import getopt

    rgb = load_rgb()
    want_desktop = want_nautilus = want_icons = 0
    color = None

    try:
        optlist, args = getopt.getopt(argv[1:], '', ['desktop', 'nautilus',
        'icons'])
    except getopt.GetoptError:
        print 'Usage:', argv[0], _usage_
        return 1
    
    for key, value in optlist:
        if key == '--desktop':
            want_desktop = 1
        if key == '--nautilus':
            want_nautilus = 1
        if key == '--icons':
            want_icons = 1
            
    try:
        color = rgb[args[0].lower()]
    except KeyError, ValueError:
        color = (int(args[0]), int(args[1]), int(args[2]))
    except IndexError:
        color = None
    except:
        print "unknown color specification"
        return 1
    
    if len(optlist) == 0:
        want_desktop = want_nautilus = want_icons = 1
    
    conf = gconf.client_get_default()
    if want_desktop:
        set_desktop(conf, color)
    if want_nautilus:
        set_nautilus(conf, color)
    if want_icons:
        set_icons(conf, color)

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))

