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

"""
setup via umc
"""

from __future__ import print_function
import sys
import time
import json
from argparse import ArgumentParser

from univention.lib.umc import Client
from univention.config_registry import ConfigRegistry


def watch_progress():
	fname = '/var/www/ucs_setup_process_status.json'
	waited = 0
	last_info = None
	while waited <= 360:
		time.sleep(10)
		waited += 1
		try:
			new_info = json.load(open(fname))
		except EnvironmentError:
			if last_info is not None:
				break
			print('Could not read %s' % fname)
			last_info = None
			continue
		except ValueError:
			print('Could not read %s' % fname)
			last_info = None
			continue
		if new_info and last_info != new_info:
			print(new_info)
			last_info = new_info
	else:
		raise RuntimeError('Did not finish within an hour!')


def start_setup(username, password, profile):
	client = Client(username=username, password=password)
	path = 'setup/join'
	print('-> invoke {path} with options {data}'.format(path=path, data=profile))
	print('-> headers: {headers}'.format(headers=client._headers))
	resp = client.umc_command(path, {'values': profile}, flavor='wizard')
	assert resp.status == 200
	result = resp.result
	print('<- {res}'.format(res=result))
	return client


def load_profile(filename):
	data = dict()
	ucr = ConfigRegistry()
	interfaces = dict()
	with open(filename, 'r') as profile:
		for line in profile:
			line = line.strip()
			if not line:
				continue
			if line.startswith('#'):
				continue
			key, value = line.split('=', 1)
			for delim in ("'", '"'):
				if value.startswith(delim) and value.endswith(delim):
					value = value[1:-1]
					break
			if ucr.is_true(value=value.lower(), default=False):
				value = True
			elif ucr.is_false(value=value.lower(), default=False):
				value = False
			elif not value:
				value = None
			if key.startswith('interfaces'):
				iface = key.split('/')
				if len(iface) > 2:
					if iface[1] not in interfaces:
						interfaces[iface[1]] = dict()
					interfaces[iface[1]][iface[2]] = value
				else:
					data[key] = value
			else:
				data[key] = value
	data['interfaces'] = interfaces
	json.dumps(data)  # just check
	return data


def main(args=None):
	description = sys.modules[__name__].__doc__
	parser = ArgumentParser(description=description)
	parser.add_argument('-U', '--username', default='root')
	parser.add_argument('-p', '--password', default='univention')
	parser.add_argument('--profile-file', help='ucs profile file', default='/var/cache/univention-system-setup/profile.bak')
	args = parser.parse_args(args)
	profile = load_profile(args.profile_file)
	start_setup(args.username, args.password, profile)
	watch_progress()
	return True

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