#!/usr/bin/python
#
# Copyright (C) 2010-2012 Red Hat, Inc.
# Authors:
# Thomas Woerner <twoerner@redhat.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, 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, see <http://www.gnu.org/licenses/>.
#
# python fork magic derived from setroubleshoot
# Copyright (C) 2006,2007,2008,2009 Red Hat, Inc.
# Authors:
#   John Dennis <jdennis@redhat.com>
#   Dan Walsh <dwalsh@redhat.com>

import os
import sys
import dbus
import syslog
import traceback

from firewall import config
from firewall.errors import *
from firewall.functions import firewalld_is_active
from firewall.core.logger import log, FileLog

debug = 0
fork = True

args = sys.argv[1:]

def usage(code):
    print(_("Usage: %s [-h|--help] [--debug[=<level>]] [--nofork]") % \
              sys.argv[0])
    sys.exit(code)

# check for root user
if os.getuid() != 0:
    print(_("You need to be root to run %s.") % sys.argv[0])
    sys.exit(-1)

for arg in args:
    if arg in ["-h", "--help"]:
        usage(0)
    elif arg == "--debug":
        debug = 1
    elif arg[:8] == "--debug=":
        try:
            debug = int(arg[8:])
        except:
            usage(1)
    elif arg == "--nofork":
        fork = False
    else:
        print(_("Unknown option '%s'") % arg)
        usage(2)


log_file = FileLog(config.FIREWALLD_LOGFILE, "a")
log.setDateFormat("%Y-%m-%d %H:%M:%S")
log.setFormat("%(date)s %(label)s%(message)s")
log.setInfoLogging("*", log.syslog, [ log.FATAL, log.ERROR ])
log.addInfoLogging("*", log_file, [ log.FATAL, log.ERROR ])
log.setInfoLogging("*", log_file, [ log.WARNING ])
log.setDebugLogLevel(log.NO_INFO)
log.setDebugLogLevel(log.NO_DEBUG)
log.setDebugLogging("*", log_file, [ i for i in xrange(1, log.DEBUG_MAX+1) ])

if debug:
    if debug > log.DEBUG_MAX:
        debug = log.DEBUG_MAX
    log.setInfoLogLevel(log.INFO_MAX)
    log.setDebugLogLevel(debug)
    log.addInfoLogging("*", log_file)
    log.addDebugLogging("*", log_file)
    if not fork:
        log.addInfoLogging("*", log.stdout)
        log.addDebugLogging("*", log.stdout)
        

if firewalld_is_active():
    log.fatal(_("Not starting FirewallD, already running."))
    sys.exit(1)

try:
    if fork:
        # do the UNIX double-fork magic, see Stevens' "Advanced 
        # Programming in the UNIX Environment" for details (ISBN 0201563177)
        pid = os.fork()
        if pid > 0:
            # exit first parent
            sys.exit(0)

        # decouple from parent environment
        os.chdir("/")
        os.setsid()
        os.umask(os.umask(0077) | 0022)
    
    # write the pid file
    pid_file = "/var/run/firewalld.pid"
    f = open(pid_file, "w")
    f.write(str(os.getpid()))
    f.close()

    # import here
    from firewall.server import server
    server.run_server()

except OSError, e: 
    log.fatal(_("Fork #1 failed: %d (%s)") % (e.errno, e.strerror))
    log.error(traceback.format_exc())
    os.remove(pid_file)
    sys.exit(1)

except dbus.DBusException, e:
    log.fatal(str(e))
    log.error(traceback.format_exc())
    os.remove(pid_file)
    sys.exit(1)

except IOError, e:
    log.fatal(str(e))
    log.error(traceback.format_exc())
    os.remove(pid_file)
    sys.exit(1)

os.remove(pid_file)
sys.exit(0)
