#!/usr/bin/python2

# Crunchbang Openbox Logout
#   - GTK/Cairo based logout box styled for Crunchbang
#
#    Andrew Williams <andy@tensixtyone.com>
#
#    Originally based on code by:
#       adcomp <david.madbox@gmail.com>
#       iggykoopa <etrombly@yahoo.com>
#
#    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.
#
#    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.,
#    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#

import os
import sys
import getopt
import logging
import logging.handlers
from oblogout import OpenboxLogout
     
class Usage(Exception):
    def __init__(self, msg):
        self.msg = msg

def main(argv = None):
    
    # Start logger instace used by the OpenboxLogout class
    logger = logging.getLogger()
    logout = logging.StreamHandler(sys.stdout)
    logout.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
    logger.addHandler(logout)
    
    verbose = None
    config = None
    local_mode = None
    
    if argv is None:
        argv = sys.argv

    try:
        try:
            opts, args = getopt.getopt(argv[1:], "hvc:l", ["help", "verbose", "config=", "local"])
        except getopt.error, msg:
             raise Usage(msg)
        # more code, unchanged
    except Usage, err:
        logger.error(err.msg)
        logger.error("for help use --help")
        return 2

    for o, a in opts:
        if o in ("-h", "--help"):
            print __doc__
            return 0
        elif o in ("-v", "--verbose"):
            verbose = True
        elif o in ("-c", "--config"):
            config = a
        elif o in ("-l", "--local"):
            local_mode = True

    if not config:
        if not local_mode:
            config = '/etc/oblogout.conf'
        else:
            config = 'data/oblogout.conf'
                
    # Check config in local path, if it exists pass it on     
    if not os.path.exists(config):
        logger.error("Invalid config file: %s" % config)
        return 1

    # If debug mode is enabled, output debug messages
    if verbose:
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)

    # Start the application
    app = OpenboxLogout(config, local_mode)
    app.run_logout() 
    return 0

if __name__ == "__main__":
    sys.exit(main())

