#!/usr/bin/env python3
import os
import send_lib
import sys
import requests
import json

SERVICE_NAME = "bbmri_networks"
TIMEOUT = 5400  # 90s * 60 sec = 1.5h

send_lib.check_input_fields(sys.argv, True)

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

send_lib.check_destination_type_allowed(destination_type, send_lib.DESTINATION_TYPE_URL)
send_lib.check_destination_format(destination, destination_type)

gen_folder = send_lib.get_gen_folder(facility, SERVICE_NAME)
user_file_name = "users.scim"
group_file_name = "groups.scim"
user_filepath = os.path.join(gen_folder, user_file_name)
group_filepath = os.path.join(gen_folder, group_file_name)
user_endpoint = "users"
group_endpoint = "mapping"


# Read username and password from configuration if it is present - else auth is not added to the request
auth = send_lib.get_auth_credentials(SERVICE_NAME, destination)

with open(user_filepath, 'rb') as f:
	headers = {'Content-Type': 'application/json'}
	response = requests.post(destination + user_endpoint, headers=headers, auth=auth, timeout=TIMEOUT, json=json.load(f))
	if response.status_code == 124:
		send_lib.die_with_error("Propagation users - Communication with the peer has timed out with return code:"
								" 124 (Warning: this error can mask original error 124 from peer!)")
	if not response.ok:
		send_lib.die_with_error(
			"Propagation users - Communication with the peer ends with return code: " + str(response.status_code))

with open(group_filepath, 'rb') as f:
	headers = {'Content-Type': 'application/json'}
	response = requests.post(destination + group_endpoint, headers=headers, auth=auth, timeout=TIMEOUT, json=json.load(f))
	if response.status_code == 124:
		send_lib.die_with_error("Propagation groups - Communication with the peer has timed out with return code:"
								" 124 (Warning: this error can mask original error 124 from peer!)")
	if not response.ok:
		send_lib.die_with_error(
			"Propagation groups - Communication with the peer ends with return code: " + str(response.status_code))
