#!/usr/bin/python
#
# Copyright 2009 Marcelo Boveto Shima.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA    02110-1301, USA.
#
# Author: marceloshima@gmail.com (Marcelo Boveto Shima)

import tacix.backend.TXManager
import sys
import os
import os.path
import atexit
import time
import string

PIDFILE='/var/run/tacix-manager.pid'

def daemonize (pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
 
    '''This forks the current process into a daemon. The stdin, stdout, and
    stderr arguments are file names that will be opened and be used to replace
    the standard file descriptors in sys.stdin, sys.stdout, and sys.stderr.
    These arguments are optional and default to /dev/null. Note that stderr is
    opened unbuffered, so if it shares a file with stdout then interleaved
    output may not appear in the order that you expect. '''
 
    if os.path.exists(pidfile):
        pid = file(pidfile,'r').read()
        pid = string.replace(pid, "\n", "")
        try:
            os.kill(int(pid), 0)
            print("daemon is running")
            sys.exit(0)
        except OSError, e:
            print("pidfile exists but daemon is not running")
            delpid()

    # Do first fork.
    try:
        pid = os.fork()
        if pid > 0:
            time.sleep(1)
            sys.exit(0)   # Exit first parent.
    except OSError, e:
        sys.stderr.write ("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror) )
        sys.exit(1)
 
    # Decouple from parent environment.
    os.chdir("/")
    os.umask(0)
    os.setsid()
 
    # Do second fork.
    try:
        pid = os.fork()
        if pid > 0:
            time.sleep(1)
            sys.exit(0)   # Exit second parent.
    except OSError, e:
        sys.stderr.write ("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror) )
        sys.exit(1)
 
    # Now I am a daemon!
 
    # Redirect standard file descriptors.
    si = open(stdin, 'r')
    so = open(stdout, 'a+')
    se = open(stderr, 'a+', 0)
    os.dup2(si.fileno(), sys.stdin.fileno())
    os.dup2(so.fileno(), sys.stdout.fileno())
    os.dup2(se.fileno(), sys.stderr.fileno())

    # write pidfile
    atexit.register(delpid)
    pid = str(os.getpid())
    file(pidfile,'w+').write("%s\n" % pid)

def delpid ():
    os.remove(PIDFILE);
 
def main ():
    server = tacix.backend.TXManager.TXManager()
    sys.exit(server.run())
 
if __name__ == "__main__":
    daemonize(PIDFILE)
    main()
