#!/usr/bin/python3

import sys
import json
import time
import urllib.request


from univention.config_registry import ConfigRegistry

port = ConfigRegistry().load().get('appcenter/apps/relution/ports/8080')

class MethodRequest(urllib.request.Request):
	def __init__(self, *args, **kwargs):
		try:
			self._method = kwargs.pop('method')
		except KeyError:
			self._method = None
		return super().__init__(*args, **kwargs)

	def get_method(self, *args, **kwargs):
		if self._method is not None:
			return self._method
		return super().get_method(*args, **kwargs)


def relution_request(method, url, data=None):
	headers = {
		'Content-Type': 'application/json',
		'Accept': 'application/json',
		}
	if data:
		data = json.dumps(data)
	request = MethodRequest('http://localhost:' + port + url, data, headers, method=method)
	print('%s %s' % (method, url))
	return urllib.request.urlopen(request)


if __name__ == '__main__':
	if len(sys.argv) > 2 and sys.argv[1] != 'install' and sys.argv[1] != 'upgrade':
		sys.exit(0)
	i = 0
	print('Waiting for Relution to start (max 30 minutes)')
	while i < 600:
		try:
			print('Checking availability')
			if relution_request('GET', '/gofer/system/security/currentAuthorization') is None:
				raise RuntimeError('Not yet started...')
		except:
			i += 1
			time.sleep(3)
			sys.stdout.flush()
		else:
			break
	else:
		print('Relution did not respond in time!')
		sys.exit(2)
	print('Relution started.')
