#!/usr/bin/python2.7
#
# Univention Network Common
#  Save the ip address in LDAP
#
# Copyright (C) 2012-2014 Univention GmbH
#
# http://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.

import os, sys, time, string
import optparse
import ipaddr
import netifaces
import subprocess
import univention.config_registry
import univention.uldap

def register_iface(configRegistry, iface, verbose):
	# is fallback different from current address?
	p1 = subprocess.Popen(['/usr/sbin/umc-command', '-U', '%s$' % configRegistry.get('hostname'), '-y', '/etc/machine.secret', '-s', configRegistry.get('ldap/master'), 'ip/change', '-o' ,'ip=%s' % configRegistry.get('interfaces/%s/address' % iface), '-o', 'oldip=%s' % configRegistry.get('interfaces/%s/fallback/address' % iface), '-o', 'netmask=%s' % configRegistry.get('interfaces/%s/netmask' % iface), '-o',  'role=%s' % configRegistry.get('server/role')], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
	res = p1.communicate()
	if p1.returncode != 0:
		print 'ERROR: IP registration for %s failed with code %s' % (iface,p1.returncode)
		if verbose:
			print 'More information: %s\n%s' % (res[1], res[0])
		return False
	else:
		# change fallback
		ucr_set = []
		for k in ['type', 'address', 'network', 'broadcast', 'netmask']:
			if configRegistry.get('interfaces/%s/%s' % (iface, k)) != configRegistry.get('interfaces/%s/fallback/%s' % (iface, k)):
				value = configRegistry.get('interfaces/%s/%s' % (iface, k))
				ucr_set.append('interfaces/%s/fallback/%s=%s' % (iface, k, value))
		if ucr_set:
			null = open(os.path.devnull, 'w' )
			stdout = sys.stdout
			sys.stdout = null

			# Disable ifdown / ifup while setting new UCR variables to avoid an endless loop
			restart = configRegistry.get('interfaces/restart/auto', 'true')
			univention.config_registry.handler_set(['interfaces/restart/auto=false'], quiet=True)

			# Set values
			univention.config_registry.handler_set(ucr_set, quiet=True)

			univention.config_registry.handler_set(['interfaces/restart/auto=%s' % restart], quiet=True)
			sys.stdout = stdout
	return True

if __name__ == '__main__':

	parser = optparse.OptionParser( )
	parser.add_option("--interface", dest="interface", default='all', action="store", help="network interface to use")
	parser.add_option("--verbose", dest="verbose", default=False, action="store_true", help="verbose output")
	parser.add_option("--force", dest="force", default=False, action="store_true", help="register interface even if it is configured static")
	(options, args) = parser.parse_args()

	configRegistry = univention.config_registry.ConfigRegistry()
	configRegistry.load()

	retcode = 0

	if options.interface == 'all':
		ifaces = netifaces.interfaces()
	else:
		ifaces = [options.interface]

	ifaces.remove('lo')
	if not ifaces:
		print 'ERROR: no valid interface was given. Try --interface'
		sys.exit(1)

	for iface in ifaces:
		if configRegistry.get('interfaces/%s/type' % iface) == 'dhcp' or options.force:
			if not register_iface(configRegistry, iface, options.verbose):
				retcode += 1
		elif options.verbose:
			print 'INFO: %s is not configured as dhcp device.' % iface

	sys.exit(retcode)
