#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import re
import sys
import subprocess
import smtplib
import ssl

from univention.config_registry import ConfigRegistry
from univention.config_registry.frontend import ucr_update

ucr = ConfigRegistry()
ucr.load()


def set_status(status):
	ucr_update(ucr, {'mail/relayhost/status': status})


if not ucr.is_true('mail/relayhost/managed'):
	set_status('Not touching the configuration (the App Center is neither enabling nor disabling it)')
	sys.exit(0)

relay_host = ucr.get('mail/relayhost')
relay_host_fqdn = relay_host and re.sub(r':\d+$', '', relay_host)

use_tls = ucr.get('mail/postfix/tls/client/level')

username = ucr.get('mail/relayauth/username')
try:
	with open('/etc/mailserver-relayhost.secret') as fd:
		password = fd.read().rstrip('\n')
except EnvironmentError:
	password = None

auth_file = '/etc/postfix/smtp_auth'

if relay_host_fqdn and username and password:
	ucr_update(ucr, {'mail/relayauth': 'yes'})
	content = []
	try:
		with open(auth_file) as fd:
			for line in fd:
				if line.startswith('%s ' % relay_host_fqdn) or line.startswith('%s\t' % relay_host_fqdn):
					continue
				content.append(line)
	except EnvironmentError:
		pass
	content.append('%s %s:%s\n' % (relay_host_fqdn, username, password))
	try:
		open(auth_file, 'wb')
		os.chown(auth_file, 0, 0)
		os.chmod(auth_file, 0440)
		with open(auth_file, 'wb') as fd:
			for line in content:
				fd.write(line)
	except EnvironmentError as exc:
		print 'Failed to write %s: %s' % (auth_file, exc)
else:
	try:
		os.unlink(auth_file)
		os.unlink(auth_file + '.db')
	except EnvironmentError:
		pass
	ucr_update(ucr, {'mail/relayauth': 'no'})

print 'Checking the configuration'
if relay_host:
	try:
		try:
			smtp = smtplib.SMTP(relay_host)
		except smtplib.SMTPException:
			smtp = smtplib.SMTP_SSL(relay_host)
		else:
			try:
				smtp.starttls()
			except smtplib.SMTPException:
				if use_tls == 'must':
					raise
		if username and password:
			code, msg = smtp.login(username, password)
			if not 200 <= code < 300:
				raise smtplib.SMTPException('Auth failed')
	except (ssl.SSLError, smtplib.SMTPException) as exc:
		set_status('Relay host configured, but a login test failed (%s)!' % exc)
	else:
		set_status('Relay host successfully configured')
else:
	set_status('Relay host disabled')

if os.path.exists(auth_file):
	sys.exit(subprocess.call(['postmap', auth_file]))
subprocess.call(['service', 'postfix', 'reload'])
