#!/usr/bin/env python

import os
import sys
import json
import time
import base64
import urllib2


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

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


def _get_credentials():
	return 'admin', os.environ.get('SYSTEM_ADMIN_PASSWORD', '')


def relution_request(method, url, data=None):
	username, password = _get_credentials()
	creds = base64.b64encode('%s:%s' % (username, password))
	headers = {
		'Content-Type': 'application/json',
		'Accept': 'application/json',
		'Authorization': 'Basic %s' % creds
		}
	if data:
		data = json.dumps(data)
	request = MethodRequest('http://localhost:8080' + url, data, headers, method=method)
	print('%s %s' % (method, url))
	return urllib2.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.')
