#!/usr/bin/env python3

import subprocess
import sys
import os
import multiprocessing

RED5_HOME="%%RED5_HOME%%/"
TOKEN="/run/lliurex-openmeetings-service"

def usage():
	
	print("lliurex-openmeetings-service { start | stop | status }")
	sys.exit(0)

def write_token():
	
	f=open(TOKEN,"w")
	f.write(str(os.getpid()))
	f.close()

def delete_token():
	
	try:
		os.remove(TOKEN)
	except Exception as e:
		pass
	
def check_token():
	
	return os.path.exists(TOKEN)

	
def launch_service():
	
	if not check_token():
	
		p=multiprocessing.Process(target=_launch_service)
		p.start()
		
	else:
		
		print ("RUNNING")
	
	
def _launch_service():
	
	LOG_DIR="/var/log/openmeetings/"
	
	if not os.path.exists(LOG_DIR):
		os.mkdir(LOG_DIR)
	#Openmeetings now is controlled by startup.sh
#	cmd="cd %s ; RED5_HOME=%s %sred5.sh"%(LOG_DIR,RED5_HOME,RED5_HOME)
	cmd="/var/lib/openmeetings/bin/startup.sh"
#	p=subprocess.Popen([cmd],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
	p=subprocess.run([cmd])
	if p.returncode==0:
		print ("RUNNING")

#	while True:
#		if "Openmeetings is up" in p.stdout.readline():
#			print "RUNNING"
#			break
			
def stop_service():
	
	if check_token():
	
#		cmd="RED5_HOME=%s %sred5-shutdown.sh 1>/dev/null 2>/dev/null"%(RED5_HOME,RED5_HOME)
		cmd="/var/lib/openmeetings/bin/shutdown.sh"
		p=subprocess.run([cmd])
#		os.system(cmd)

if len(sys.argv)>1:

	if sys.argv[1]=="start":
		
		launch_service()
		write_token()
		
		
	if sys.argv[1]=="stop":

		stop_service()
		delete_token()
		print("STOPPED")
		
	if sys.argv[1]=="status":
		
		if check_token():
			print("RUNNING")
		else:
			print("STOPPED")
		
else:
	
	usage()
	
	
	



