#!/usr/bin/python -E

#
# Copyright (C) 2006 Red Hat, Inc.
#
# 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., 675 Mass Ave, Cambridge, MA 02139, USA.
#

import os
import getopt
import sys

def usage():
    print '''
-f no fork
-h help
'''

fork = True

try:
    opts, args = getopt.getopt(sys.argv[1:], "fh", ["nofork","help"])
except getopt.GetoptError:
    # print help information and exit:
    usage()
    sys.exit(2)

for o, a in opts:
    if o in ("-h", "--help"):
        usage()
        sys.exit()
    if o in ("-f", "--nofork"):
        fork = False

if fork:
    # do the UNIX double-fork magic, see Stevens' "Advanced 
    # Programming in the UNIX Environment" for details (ISBN 0201563177)
    try: 
        pid = os.fork() 
        if pid > 0:
            # exit first parent
            sys.exit(0) 
    except OSError, e: 
        print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror) 
        sys.exit(1)

    from setroubleshoot.config import cfg
    # decouple from parent environment
    os.chdir("/") 
    os.setsid() 
    os.umask(os.umask(0077) | 0022)

    # write the pid file
    pid_file = cfg.get('general','pid_file')
    f=open(pid_file, "w")
    f.write(str(os.getpid()))
    f.close()

from setroubleshoot.server import RunFaultServer
RunFaultServer()

