#!/usr/bin/python

import sys
import os
import pwd
import time
import subprocess

def log_this(s):
    """
    Prepend the argument with a time stamp and print it.
    """

    print time.strftime("%b %e %H:%M:%S ") + s

class Log:
    """
    File like for writes with auto flush after each write
    to ensure that everything is logged, even during an
    unexpected exit.
    """

    def __init__(self, f):
        self.f = f

    def write(self, s):
        self.f.write(s)
        self.f.flush()

def deamonize(logfile, pidfile):
    """
    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:
            sys.exit(0)
    except OSError, e:
        print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror)
        sys.exit(1)

    os.chdir("/")           # Don't prevent unmounting....
    os.setsid()
    os.umask(022)

    try:
        pid = os.fork()
        if pid > 0:
            open(pidfile, 'w').write("%d\n" % pid)
            sys.exit(0)
    except OSError, e:
        print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
        sys.exit(1)

    os.close(sys.stdin.fileno())
    os.close(sys.stdout.fileno())
    os.close(sys.stderr.fileno())

    sys.stdout = sys.stderr = Log(open(logfile, 'a+'))

def run_subprocess(args):
    
    log_this("Running %s" %  os.path.basename(args[0]))

    p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    
    lines  = p.stdout.readlines()
    errs   = p.stderr.readlines()
    status = p.wait()
    

    for l in lines:
        log_this("subprocess stdout: " + l.strip())

    for l in errs:
        log_this("subprocess stderr: " + l.strip())

    if status != 0:
        log_this("process failed")
    else:
        log_this("process complete")
        
    return status

def main():
    """
    Read the arguments and start the server.
    """

    myname = os.path.basename(sys.argv[0])
    mypath = os.path.realpath(os.path.dirname(sys.argv[0]))

    args = (mypath + os.sep + "service", )

    # All output on stdout.

    log_this("first try ... succeeds")

    status = run_subprocess(args)

    logfile = '/tmp/' + myname + '.log'
    pidfile = '/tmp/' + myname + '.pid'

    deamonize(logfile, pidfile)

    # All output on logfile.

    log_this("second try ... fails")

    status = run_subprocess(args)

if __name__ == '__main__':
    main()
