#!/usr/bin/python

import sys
import os
import signal
import subprocess
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read("../cfg/forban.cfg")
forbanpath = config.get('global','path')

def service_start(servicename = None):
    if servicename is not None:
        service = servicename+".py"
        proc =  subprocess.Popen(["python",service])
        return proc.pid
    return False

def writepid (processname = None, pid = None):
    pidpath = forbanpath+"/var/"+processname+".pid"
    if processname is not None and pid is not None:
        f = open (pidpath,"w")
        f.write(str(pid))
        f.close()
        return True
    else:
        return False

def pidof(processname = None):
    pidpath = forbanpath+"/var/"+processname+".pid"
    if processname is not None and os.path.exists(pidpath):
        f = open (pidpath)
        pid = f.read()
        f.close()
        return pid
    else:
        return False

def usage():
    print "forbanctl (start|stop)"
    exit (1)

if len(sys.argv) < 2:
    usage()

forban_services = ["forban_discover", "forban_announce", "forban_share", "forban_opportunistic"]

if sys.argv[1] == "start":

    print "Starting Forban services..."
    for service in forban_services:
        if not ((config.get('global','mode') == "shared")  and (service == "forban_opportunistic")):
            print service+"to start..."
            pid = service_start(servicename = service)
            writepid(processname = service, pid = pid)
            print pidof(processname=service)

elif sys.argv[1] == "stop":

    print "Stopping Forban services..."
    for service in forban_services:
        pid = pidof(processname=service)
        if pid:
            print service+" to be stopped..."
            try:
                os.kill(int(pid), signal.SIGKILL)
            except OSError, e:
                print service+  " unsuccessfully stopped"
else:
    usage()
