#!/usr/bin/env python3

import send_lib
import sys
import re

service_name = "tinia"

send_lib.check_input_fields(sys.argv, destination_type_required=True)

facility = sys.argv[1]
destination = sys.argv[2]
destination_type = sys.argv[3]

send_lib.check_destination_type_allowed(destination_type, "service-specific")
send_lib.check_destination_format(destination, destination_type, send_lib.SIMPLE_PATTERN)

#Destination is name of database on oracle in localhost tnsnames file
dbname = destination

service_files_dir = send_lib.get_gen_folder(facility, service_name)
send_lib.create_lock(service_name, dbname)

#  copy service file to temporary directory
with send_lib.prepare_temporary_directory() as tmp_dir:
	send_lib.copy_files_to_directory(service_files_dir, tmp_dir, re.compile(service_name))
	scriptpath = "./tinia_process.pl"
	process = send_lib.exec_script(scriptpath, ["-d", dbname, "-p", tmp_dir, "-s", service_name])
	process.wait()
	stdout, stderr = process.communicate()
	print(stdout.decode("utf-8"), end='')
	print(stderr.decode("utf-8"), file=sys.stderr, end='')
	if process.returncode != 0:
		send_lib.die_with_error("Slave script ends with return code: " + str(process.returncode))
