#!/usr/bin/python2.7
# -*- coding: utf-8 -*-

"""
upload license via umc to activate appliance
"""

from __future__ import print_function
import sys
import json
import requests

from argparse import ArgumentParser
from univention.config_registry import ConfigRegistry
from univention.appcenter.app_cache import AppCenterCache

def upload_license(license, ucr, notify_apps):
	hostname = '%s.%s' % (ucr.get('hostname'), ucr.get('domainname'))
	response = requests.post('https://{}/license'.format(hostname), files=dict(license=license))
	print(notify_apps)
	print(response)
	print(response.content)
	print(response.status_code)
	assert response.status_code == 200
	c = json.loads(response.content)
	assert c['success'] is True
	send_notification_for = [app[0] for app in c['apps']]
	for app in notify_apps:
		assert app in send_notification_for
	return True


def main(args=None):
	description = sys.modules[__name__].__doc__
	parser = ArgumentParser(description=description)
	parser.add_argument('-l', '--license-file', default='./ValidTest.license')
	parser.add_argument('apps', metavar='app', type=str, nargs='+', help='apps')
	args = parser.parse_args(args)
	cache = AppCenterCache()
	notify_apps = []
	for app in args.apps:
		info = cache.find(app)
		if info.notify_vendor:
			notify_apps.append(app)
	ucr = ConfigRegistry()
	ucr.load()
	with open(args.license_file, 'r') as f:
		license = f.read()
	upload_license(license, ucr, notify_apps)
	return True

if __name__ == '__main__':
	if not main():
		sys.exit(1)
