import sys
import os
from json import load as jsonDec

# File config
startRecordPath = '$HOME/Documentos/centroGEO/GStreamer_audioRecorder/production/helloworld.sh'
startRecordFile = '$HOME/Documentos/centroGEO/GStreamer_audioRecorder/production/helloworld'

# Streams owners file
streamPublishersFile = 'streamPublishers.json'

# File that saves the recorders pid
PIDSFile = 'streamsPIDS.txt'


#  Child
def startStream(publisher_url, record_time):
	print('\nA new child ',  os.getpid())
	os.execl(startRecordPath, startRecordFile, publisher_url, record_time)
	os._exit(0)

# Parent
def streamsInitializer(record_time):

	with open(streamPublishersFile) as data:
		publishers_data = jsonDec(data)

	pids_file = open(PIDSFile, "w")

	for i in range(len(publishers_data)):
		new_pid = os.fork()
		if(new_pid == 0):
			startStream(publishers_data[i]["url"], str(record_time))
		else:
			pids = (os.getpid(), new_pid)
			pids_file.write(str(new_pid) + "\n")
			print("parent: %d, child: %d\n" % pids)
			
	pids_file.close()


def main():

	if(len(sys.argv) < 2):
		print("Record time required - eg. python startRecorders.py 60")
	else:
		record_time = sys.argv[1]
		streamsInitializer(record_time)

if __name__ == '__main__':
	main()