#!/usr/bin/env python  
# encoding: utf-8
#
# +--------------------------------------------------------------------------+
# | Endian Firewall                                                          |
# +--------------------------------------------------------------------------+
# | Copyright (c) 2005-2011 Endian                                           |
# |         Endian GmbH/Srl                                                  |
# |         Bergweg 41 Via Monte                                             |
# |         39057 Eppan/Appiano                                              |
# |         ITALIEN/ITALIA                                                   |
# |         info@endian.com                                                  |
# |                                                                          |
# | endian-core is free software: you can redistribute it and/or modify      |
# | it under the terms of GNU General Public License (GPL) version 2.0       |
# | when released with the Community edition                                 |
# | or the GNU Lesser General Public License (LGPL) version 2.1              |
# | when released with the Enterprise edition.                               |
# |                                                                          |
# | endian-core 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 or the                       |
# | GNU Lesser General Public License for more details.                      |
# |                                                                          |
# | You should have received a copy of the license along with endian-core.   |
# | If not, see <http://www.gnu.org/licenses/>.                              |
# +--------------------------------------------------------------------------+
#
#  ticket
#
#  Created by Peter Warasin on 2008-07-22
#

from endian.firewall.ticket import TicketRegistry
from endian.core.logger import *
from optparse import OptionParser
import sys
import os

def opthandler():
    usage = "usage: %prog [options] <--register|--unregister> <item>"
    parser = OptionParser(usage)
    parser.add_option("-d", "--debug", dest="debug",
                      action="store_true",
                      help="be more verbose", default=False)
    parser.add_option("-f", "--file", dest="file",
                      help="store tickets in file FILE", metavar="FILE")
    parser.add_option("-R", "--realm", dest="realm",
                      help="store tickets in realm REALM (default: 0)",
                      metavar="REALM", default="0")
    parser.add_option("-s", "--startid", dest="startid", default="0",
                      help="start tickets with id #ID", metavar="ID")
    parser.add_option("-r", "--register", dest="register",
                      action="store_true", default=False,
                      help="Register the item")
    parser.add_option("-u", "--unregister", dest="unregister",
                      action="store_true", default=False,
                      help="Unregister the item")
    parser.add_option("-a", "--all", dest="flush",
                      action="store_true", default=False,
                      help="Unregister all items of the realm")

    (o, a) = parser.parse_args()

    if o.file == None:
        parser.error("--file need to be set")
    try:
        o.startid = int(o.startid) 
    except ValueError:
        parser.error("need to be an integer")
    if o.register and (o.unregister or o.flush):
        parser.error("--register can't be used together with "
                     "--unregister or --all")

    if a == None or len(a) == 0:
        parser.error("An item need to be supplied")

    return (o, a[0])
                      
def do(o,a):
    dir = os.path.dirname(o.file)
    if dir != "":
        if not os.path.exists(dir):
            error("Path \"%s\" does not exist"%dir)
            sys.exit(1)
    try:
        debug("Use registry \"%s\""%o.file)
        r = TicketRegistry(o.file, o.startid)
        if o.flush:
            debug("Unregister all items from realm \"%s\""%o.realm)
            r.unregisterAll(o.realm)
        if o.unregister:
            debug("Unregister item \"%s\" from realm \"%s\""%(a,o.realm))
            r.unregister(a, o.realm)
        if o.register:
            debug("Register item \"%s\" to realm \"%s\""%(a,o.realm))
            id = r.register(a, o.realm)
            debug("Got id \"%s\""%id)
            print id
    except Exception, e:
        import traceback
        debug(traceback.format_exc())
        error(e)
        sys.exit(1)
    debug("Done")
    sys.exit(0)
    

(options, item) = opthandler()
if options.debug:
    logger.setLevel(logging.DEBUG)
else:
    logger.setLevel(logging.INFO)
do(options,item)
