#!/usr/bin/python

# update-configlets --Script for updating configlet information

# $Progeny$

# Copyright (C) 2001  Progeny Linux Systems, Inc.
# AUTHORS: Jeff Licquia <jlicquia@progeny.com>

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2,  as
# published by the Free Software Foundation.

# 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 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

# TODO: A third mode, similar to Jeff's original mode, when the
# configlet package is first installed there may already be configlets
# on the system.  So update-configlets will need a mode to scan for
# all existing configlets and do the setup work.  It also needs to
# tear down that stuff upon removal.

import os
import string
import sys
import getopt
import configlet

desktop_template = [ "[Desktop Entry]",
                     "Name=<configlet-title>",
                     "Comment=<configlet-desc>",
                     "Exec=<configlet-dirname>-configlet-capplet",
                     "Terminal=0",
                     "Type=Application" ]

desktop_directories = ["/usr/share/control-center/Debian",
                       "/usr/share/gnome/apps/Settings/Debian"]

base_config_capplet = "/usr/bin/configlet-capplet"
default_configlet_path = "/usr/share/configlets"

do_install = 0
do_remove = 0
do_all = 0
configlet_name = ""

configlet_list_filename = "/var/cache/configlet-frontends/configlet-capplet.list"
configlet_list = []

def debug(msg):
    if os.environ.has_key("DEBUG"):
        sys.stderr.write("update-configlet-frontends: %s\n" % (msg,))

def warn(msg):
    sys.stderr.write("%s\n" % (msg,))

def fatal(msg):
    warn(msg)
    warn("Terminating")
    sys.exit(-1)

def usage():
    sys.stderr.write("Usage: update-configlets " +
                     "{--install|--remove|--reinstall} <configlet>\n")
    sys.stderr.write("                         " +
                     "{--install-all|--remove-all|--update}\n")
    sys.stderr.write("Where <configlet> is the directory name under " +
                     "%s\n" % (default_configlet_path,))

def parse_opts():
    global do_install
    global do_remove
    global do_all
    global configlet_name

    try:
        opts, args = getopt.getopt(sys.argv[1:], "h",
                                   ['install=', 'remove=', 'reinstall=',
                                    'install-all', 'remove-all', 'update',
                                    'help'])
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    sys.argv = [sys.argv[0]]

    if len(opts) > 1:
        usage()
        sys.exit(2)

    if len(opts) == 0:
        # Default to "--update".
        do_install = 1
        do_remove = 1
        do_all = 1
        return
    else:
        for o, a in opts:
            if o in ('-h', '--help'):
                usage()
                sys.exit(0)
            elif o in ('--install-all', '--remove-all', '--update'):
                if o == '--install-all':
                    do_install = 1
                    do_remove = 0
                elif o == '--remove-all':
                    do_install = 0
                    do_remove = 1
                else:
                    do_install = 1
                    do_remove = 1

                do_all = 1
                return

            configlet_name = a;
            do_all = 0
            if o in ('--install',):
                do_install = 1
                do_remove = 0
            elif o in ('--remove',):
                do_install = 0
                do_remove = 1
            elif o in ('--reinstall',):
                do_install = 1
                do_remove = 1
            else:
                usage()
                sys.exit(2)

def find_old_configlet_entries():
    global configlet_list

    sysdir = None
    for dir in desktop_directories:
        if os.path.exists(dir):
            sysdir = dir
            break
    if sysdir is None:
        return

    for sysfn in os.listdir(sysdir):
        if sysfn[-8:] != ".desktop":
            continue

        sysfile = open("%s/%s" % (desktop_directories[0], sysfn))
        syslines = sysfile.readlines()
        sysfile.close()

        configlet_found = 0
        for sysline in syslines:
            if sysline[:4] != "Exec":
                continue
            sysline = sysline[5:]
            if sysline.rstrip()[-18:] == "-configlet-capplet":
                configlet_list.append(sysline.rstrip()[:-18])
            break

def load_configlet_list():
    global configlet_list

    if os.path.exists(configlet_list_filename):
        configlet_list_file = open(configlet_list_filename)
        configlet_lines = configlet_list_file.readlines()
        configlet_list_file.close()

        for line in configlet_lines:
            configlet_list.append(line.rstrip())
    else:
        find_old_configlet_entries()

def save_configlet_list():
    if len(configlet_list) < 1:
        if os.path.exists(configlet_list_filename):
            os.unlink(configlet_list_filename)
    else:
        configlet_list_file = open(configlet_list_filename, "w")
        for configlet in configlet_list:
            configlet_list_file.write("%s\n" % (configlet,))

        configlet_list_file.close()

def remove_file(file):
    if os.path.exists(file):
        os.unlink(file)
    else:
        debug("No such file: %s" % (file,))


def initialize_system():
    global desktop_directories

    for sysdir in desktop_directories:
        if not os.path.exists(sysdir):
            os.mkdir(sysdir, 0755)

def remove_configlet(configlet):
    global desktop_directories

    if configlet in configlet_list:
        for sysdir in desktop_directories:
            file = "%s/%s.desktop" % (sysdir, configlet)
            remove_file(file)

        file = "/usr/bin/%s-configlet-capplet" % (configlet,)
        remove_file(file)

        configlet_list.remove(configlet)

def install_configlet(configlet_directory):
    global desktop_directories
    global base_config_capplet
    global desktop_template
    global configlet_list

    # Make certain we have everything set up (e.g. directories)
    initialize_system()

    # Load the configlet.
    if configlet_directory[0] != '/':
        cfglet_path = "%s/%s" % (default_configlet_path, configlet_directory)
    else:
        cfglet_path = configlet_directory

    real_configlet = configlet.start_configlet(cfglet_path)
    if real_configlet is None:
        return

    # Get the configlet's information.
    cfglet_title = real_configlet.get_display_title()
    cfglet_name = real_configlet.get_name()
    cfglet_desc = real_configlet.get_description()

    # Have we already added this configlet?  Don't add it twice.
    if cfglet_name in configlet_list:
        return

    # Define the list of new files to create. The first file must be the
    # configlet-capplet script/link.
    files = ["/usr/bin/%s-configlet-capplet" % (configlet_directory,),]

    for sysdir in desktop_directories:
        files.append("%s/%s.desktop" % (sysdir, configlet_directory))

    # Make certain those files don't exist yet
    for file in files:
        if os.path.exists(file):
            debug("%s already exists, overwriting" % (file,))
            os.unlink(file)

    # Grab the /usr/bin filename and create a symlink
    file = files.pop(0)
    os.symlink(base_config_capplet, file)

    # Now, create the remaining (.desktop) files

    # Create the contents for the files
    full_contents = ""
    for line in desktop_template:
        contents = string.replace(line, "<configlet-name>", cfglet_name)
        contents = string.replace(contents, "<configlet-desc>", cfglet_desc)
        contents = string.replace(contents, "<configlet-title>", cfglet_title)
        contents = string.replace(contents, "<configlet-path>", cfglet_path)
        contents = string.replace(contents, "<configlet-dirname>",
                                  configlet_directory)
        contents = contents + "\n"
        full_contents += contents

    for file in files:
        real_file = open(file, "w")
        real_file.write(full_contents)
        real_file.close()

    configlet_list.append(configlet_directory)

def remove_all_configlets():
    for configlet in configlet_list:
        remove_configlet(configlet)

def install_all_configlets():
    for dir in os.listdir(default_configlet_path):
        if not os.path.isdir("%s/%s" % (default_configlet_path, dir)):
            continue

        install_configlet(dir)

if not os.path.exists("/usr/share/control-center"):
    sys.exit(0)

parse_opts()
if not do_all and configlet_name == "":
    usage()
    sys.exit(2)

load_configlet_list()

if do_all:
    if (do_remove == 1):
        remove_all_configlets()
    if (do_install == 1):
        install_all_configlets()
else:
    if (do_remove == 1):
        remove_configlet(configlet_name)
    if (do_install == 1):
        install_configlet(configlet_name)

save_configlet_list()

# vim:set ai et sts=4 sw=4 tw=0:
