#!/usr/bin/env python

## $Id: pygmy,v 1.27 2002/05/24 13:56:34 kjetilja Exp $

## System modules
import glob, sys, string, os
from posixpath import split

## Local modules
import folder, folderops, prefs

## Must to this after import folder.py
from gtk import mainloop

##
## Function main ()
##
##    Init default preferences.  Launch main Pygmy window.
##
##
def main(args):
    # Get preferences, either default or load existing
    p = prefs.Preferences()

    # Check that the user did not press cancel on the preferences the first time
    if not os.path.exists(p.folders):
        print 'Preferences where not set, aborting.'
        return

    # 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:
            if f == 'drafts' and f not in flds:
                # Rename outbox folder and index file to drafts
                os.rename(os.path.join(p.folders, 'outbox'),
                          os.path.join(p.folders, 'drafts'))
                os.rename(os.path.join(p.folders, '.outbox.idx'),
                          os.path.join(p.folders, '.drafts.idx'))
            else:
                # 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, args)
    pygmy.mainloop()


## Entrypoint
if __name__ == "__main__":
    try:
        main(sys.argv)
    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()
