#!/usr/bin/python

#
#        +-----------------------------------------------------------------------------+
#        | Endian Firewall                                                             |
#        +-----------------------------------------------------------------------------+
#        | Copyright (c) 2005-2006 Endian                                              |
#        |         Endian GmbH/Srl                                                     |
#        |         Bergweg 41 Via Monte                                                |
#        |         39057 Eppan/Appiano                                                 |
#        |         ITALIEN/ITALIA                                                      |
#        |         info@endian.it                                                      |
#        |                                                                             |
#        | 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, or (at your option) any later version.                      |
#        |                                                                             |
#        | 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. |
#        | http://www.fsf.org/                                                         |
#        +-----------------------------------------------------------------------------+
#

from endian.core.logger import *
from endian.core.procutils import set_process_name
from uplinksdaemon import Keepalive
from endian.core.daemon import daemonize
from endian.core.pidfile import Pidfile
from endian.core.pidfile import InvalidPid
from optparse import OptionParser
import traceback
import signal
import sys

PIDFILE='/var/run/uplinksdaemon.pid'
UPLINKSDAEMONCONFIG='/etc/uplinksdaemon/uplinksdaemon.conf'

def main():

    runforever = True
    foreground = True
    pidfile = PIDFILE

    logger.setLevel(logging.INFO)

    usage = "usage: %prog <options>"
    parser = OptionParser(usage)
    parser.add_option("-p", "--pidfile", dest="pidfile",
                      help="specify where to store the pidfile", metavar="PIDFILE", default=PIDFILE)
    parser.add_option("-b", "--boot", dest="boot", action="store_true",
                      help="uplink daemon starts at boot time (obsolete)", default=False)
    parser.add_option("-f", "--foreground", dest="foreground", action="store_true",
                      help="start in foreground", default=False)
    parser.add_option("-o", "--onecycle", dest="onecycle", action="store_true",
                      help="run only one cycle", default=False)
    parser.add_option("-d", "--debug", dest="debug", action="store_true",
                      help="Logs debug information", default=False)
    parser.add_option("-l", "--logfile", dest="logfile", metavar="LOGFILE", 
                      help="Specify the file where to log")
    parser.add_option("-n", "--dry-run", dest="dryrun", action="store_true",
                      help="Dry run. Print out information what the daemon would do, but don't actually do it.", default=False)
    parser.add_option("-c", "--configfile=FILE", dest="configfile",
                      metavar="FILE", default=UPLINKSDAEMONCONFIG,
                      help="Read configuration from FILE")

    (options, args) = parser.parse_args()

    if (options.onecycle and not options.foreground):
        parser.error("--onecycle can only be used in conjunction with --foreground!")
        sys.exit(1)
    if options.pidfile != None:
        pidfile = options.pidfile

    pid=Pidfile(pidfile)
    if pid.isRunning():
        error("Another instance of Uplink daemon is already running with pid '%s'. Exiting..."%pid.pid)
        sys.exit(1)
    if options.debug:
        logger.setLevel(logging.DEBUG)
    if options.logfile:
        setLogfile(options.logfile)

    info("Boot uplinks daemon")
    k = Keepalive(config=options.configfile, dryrun=options.dryrun)
    if not options.foreground:
        debug("Uplinks daemon goes background")
        e = daemonize(stdoutlog="/dev/null",
                  stderrlog="/dev/null",
                  pidfile=None)
	if e:
	    error(errstr[1])
	debug("Demonized")
    else:
        if options.onecycle:
            info("Starting in foreground! One cycle only!")
        else:
            info("Starting in foreground!")

    set_process_name("uplinksdaemon")
    pid = Pidfile(pidfile)
    try:
        debug("Creating pid file '%s' with pid '%s'."%(pidfile, pid.mypid))
        pid.create()
    except Exception, errcode:
        error(errcode)
        debug("Error with pidfile creation. Exiting...")
        sys.exit(1)

    signum = -1
    while True:
        try:
            try:
                # reload configuration on SIGHUP
                # exit on all other signals which let run() return from
                # it's infinite loop
                signum = k.run(not options.onecycle)
                if options.onecycle:
                    info("Single cycle is finished. Exiting...")
	            break;
                else:
                    if signum == signal.SIGHUP:
                        info("Got SIGHUP. Reloading configuration files...")
                        k.reload()
                        if options.logfile:
                            reopenLogfile()
                    else:
                        info("Got signal. Exiting...")
			break
            except:
                for line in traceback.format_exc().split('\n'):
                    error("Traceback: %s"%line)
        except:
            # daemon should not crash because of tracebacks
            pass
    debug("Remove pid file '%s'"%pidfile)
    pid.remove()

main()
