#!/usr/bin/python
# Forban - a simple link-local opportunistic p2p free software
#
# For more information : http://www.foo.be/forban/
#
# Copyright (C) 2009-2010 Alexandre Dulaunoy - http://www.foo.be/
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import sys
import os
import platform
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 = os.path.join(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 rmpid (processname = None):
    pidpath = os.path.join(forbanpath,"var",processname+".pid")
    if os.path.exists(pidpath):
        os.unlink(pidpath)
        return True
    else:
        return False

def pidof(processname = None):
    pidpath = os.path.join(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 nppidof(processname = None):

    if platform.system() is not "Windows":
        #os.system("ps ax | grep forban_ | grep python | cut -d\" \" -f1 | sed -e '$!N;N;N; s/\\n/,/g'")
        return True

def usage():
    print "forbanctl (start|stop|forcestop)"
    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:
            if platform.system() == "Windows":
                import win32api
                import win32con
                phandle = win32api.OpenProcess( win32con.PROCESS_TERMINATE, 0, int(pid))
                win32api.TerminateProcess( phandle, 0)
                win32api.CloseHandle( phandle)
                rmpid(processname=service)
            else:
                try:
                    os.kill(int(pid), signal.SIGKILL)
                except OSError, e:
                    print service+  " unsuccessfully stopped"
                print service
                rmpid(processname=service)

elif sys.argv[1] == "forcestop":
    
    print "(forced) Stopping Forban services..."
    nppidof()

else:
    usage()
