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

service_name = "openstack_projects"
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]

gen_folder = send_lib.get_gen_folder(facility, service_name)
file_name = "access.json"

send_lib.check_destination_type_allowed(destination_type, send_lib.DESTINATION_TYPE_URL)
send_lib.check_destination_format(destination, destination_type)
filepath = os.path.join(gen_folder, file_name)

# 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(filepath, 'rb') as f:
	headers = {'Content-Type': 'application/json'}
	files = {file_name: f}
	response = requests.post(destination, headers=headers, auth=auth, timeout=timeout, files=files)
	if response.status_code == 124:
		send_lib.die_with_error("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("Communication with the peer ends with return code: " + str(response.status_code))
