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


import sys
import socket
import argparse

from univention.config_registry import ConfigRegistry

ucr = ConfigRegistry()
ucr.load()

class CarelessArgumentParser(argparse.ArgumentParser):
	def error(self, message):
		pass

parser = CarelessArgumentParser(description='Preinst of tine20')
parser.add_argument('--locale')
parser.add_argument('--error-file')
parser.add_argument('--old-version')

args = parser.parse_args()

if args.old_version:
	sys.exit(0)
try:
	master = ucr.get('ldap/master')
	sock = socket.create_connection((master, 6669), 60.0)
	handshake = 'Version: 2\nCapabilities: \n\n'
	sock.send(handshake)
	answer = sock.recv(100)
	if answer != handshake:
		if args.error_file:
			with open(args.error_file, 'ab') as fd:
				if args.locale == 'de':
					fd.write('Die Version des Univention Notifier auf %s ist nicht kompatibel mit dieser Version der App. Tine 2.0 kann nicht installiert werden.\n' % master)
				else:
					fd.write('The version of Univention Notifier at %s ist not compatible with this version of the App. Tine 2.0 cannot be installed.\n' % master)
		sys.exit(1)
except socket.error as ex:
	if args.error_file:
		with open(args.error_file, 'ab') as fd:
			if args.locale == 'de':
				fd.write('Das App Center konnte keine Verbindung zum Univention Notifier auf %s aufbauen. Das ist notwendig, weil diese App eine bestimmte Version des Notifiers voraussetzt. Bitte prüfen Sie die Verbindung zu %s.\n' % (master, master))
			else:
				fd.write('The App Center could not establish a connection to the Univention Notifier at %s. This is necessary as the App does need a specific version of the Notifier. Please check the connection to %s.\n' % (master, master))
	sys.exit(1)
sys.exit(0)
