#!/usr/bin/env python

## $Id: pygmy,v 1.21 2001/04/15 18:42:31 kjetilja Exp $

## System modules
import glob, sys, string
from posixpath import split
from gtk import mainloop

## Local modules
import folder, folderops, prefs, fileops


##
## Function main ()
##
##    Init default preferences.  Launch main Pygmy window.
##
##
def main():
    # Try to load the user configuration file
    import pickle, os

    homedir = fileops.gethomedir()
    configfile = os.path.join(homedir, ".pygmy-config")
    try:
        f = open(configfile)
    except:
        # No previous configuration, launch the preferences window
        p = prefs.Preferences()
        p.alistfile = os.path.join(homedir, ".pygmy-adrlist")
        p.flistfile = os.path.join(homedir, ".pygmy-filterlist")
        p.spoolfile = fileops.getmailfile()
        p.folders = os.path.join(homedir, "Mail")
        p.sigfile = os.path.join(homedir, ".signature")
        pwin = prefs.PreferencesWindow(p)
        pwin.mainloop()
    else:
        # Load previous configuration
        p = pickle.load(f)
        f.close()
        new_p = prefs.Preferences()
        v = new_p.version
        # Check if user need to upgrade the config file
        (major_n, minor_n, rev_n) = string.split(v, '.')
        (major_o, minor_o, rev_o) = string.split(p.version, '.')
        if minor_n != minor_o or major_n != major_o:
            # We have a version mismatch here, inform the user
            print "You have an old configuration file which is no"
            print "longer supported by Pygmy.  Please remove this"
            print "file before restarting Pygmy: "
            print
            print "    rm ~/.pygmy-config"
            print
            print "Note that this will _not_ cause information in"
            print "mail folders, address lists or filters to disappear."
            return
        else:
            # Do the necessary upgrades of the configuration options
            if not hasattr(p, 'confirmsend'):
                p.confirmsend = new_p.confirmsend
            if not hasattr(p, 'fillwidth'):
                p.fillwidth = new_p.fillwidth
            p.version = v


    # Find all folders in the mail directory
    flds = map( lambda x, y=split: y(x)[1],
                glob.glob(p.folders+os.sep+'*') )

    # Ensure that the default folders are present
    for f in p.default_folders:
        folderfile = os.path.join(p.folders, f)
        indexfile = os.path.join(p.folders, '.') + f + ".idx"
        if f not in flds:
            # Create default folder file
            open(folderfile, 'a').close()
            # Create the index file
            folderops.create_folder_index(folderfile)
        else:
            # The folder may exist but the index may not
            if not os.path.isfile(indexfile):
                # No index file available, create one
                try:
                    folderops.create_folder_index(folderfile)
                except:
                    print "Unable to create index for default folder: ", f
                    print "The folder exists but is not a valid Unix mailbox."
                    print "Please remove the folder file and restart Pygmy."
                    return
                
    # Check that the folder index files are up to date
    ftree = folderops.get_active_folders(p.folders)
    folderops.check_index_consistency(p.folders, ftree)

    # Invoke the folder view window
    pygmy = folder.FolderWindow(p, ftree)
    pygmy.mainloop()


## Entrypoint
if __name__ == "__main__":
    try:
        main()
    except:
        # Show some of the runtime errors in the user interface
        import StringIO, traceback, error
        out = StringIO.StringIO()
        traceback.print_exc(file=out) 
        # Show errors in a separate window
        error.ErrorWindow(out.getvalue())
        try:
            mainloop()
        except:
            print out.getvalue()
