import os, optparse, ConfigParser

def _load_options():
    config_options = ['root','dest','template']
    
    parser = optparse.OptionParser()
    # Config Options optionally kept in conf file
    parser.add_option("-r","--root", dest="root", default="Root",
            help="Set root directory name of site to ROOT.",
            metavar="ROOT")
    parser.add_option("-d","--dest", dest="dest",
            default="/var/www",
            help="Render site to  local directory DEST.", metavar="DEST")
    parser.add_option("-t","--template", dest="template",
            default="layout.tmpl",
            help="Base template of site given as TMPL", metavar="TMPL")
    # Command line only arguments
    parser.add_option("-c","--config", dest="config_file",
            default="site.config",
            help="Read config from CONFIG", metavar="CONFIG")
    parser.add_option("-f","--force-reload",action="store_true",
            dest="reload", default=False,
            help="Force reloading of all files")
    parser.add_option("-g","--generate-config",action="store_true",
            dest="generate", default=False,
            help="(Re)Generate a config file.")
    cmd_options = parser.parse_args()[0]
    cmd_settings = _nonDefaults(cmd_options,parser)
    
    # pull values from config file
    config =  ConfigParser.ConfigParser()
    config.read(cmd_options.config_file)
    if not config.has_section('site'):
        config.add_section('site')
        for opt in config_options:
            config.set('site',opt,getattr(cmd_options,opt))
    elif cmd_settings:
        for opt,val in config.items('site'):
            if opt in cmd_settings:
                config.set('site',opt,getattr(cmd_options,opt))
            else:
                setattr(cmd_options,opt,val)
    
    # generate new config file
    if cmd_options.generate:
        fp = open(cmd_options.config_file,'w')
        try:
            config.write(fp)
        finally:
            fp.close()

    # object persistence file
    cmd_options.persistence = 'site.db'
    # This needs to be run in the directory above the root of the site.
    # So lets check change directory as appropriate.
    if cmd_options.root not in os.listdir('.'):
        raise RuntimeError(('Root directory (%s) must be a subdirectory '
                            'of the current directory.') % cmd_options.root)

    return cmd_options
         
def _nonDefaults(options,parser):
    return [option.dest for option in parser.option_list
            if option.dest and option.default != getattr(options,option.dest)]

# imported by other modules to get options
options = _load_options()
 

