#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
#
# Univention Print Server
#  wrapper script for lpadmin
#
# Copyright 2004-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 sys
import re
import pwd, os
from pexpect import *
import univention.config_registry

args=sys.argv[1:]

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

lpadminexec = '/usr/sbin/lpadmin'
for path in [ '/usr/bin/enable', '/usr/sbin/cupsenable' ]:
	if os.path.exists(path):
		enableexec = path
for path in [ '/usr/sbin/accept', '/usr/sbin/cupsaccept' ]:
	if os.path.exists(path):
		acceptexec = path

if not '-h' in args:
	args = args + ['-h', 'localhost']

# read machine password
secretFile=open('/etc/machine.secret','r')
pwdLine=secretFile.readline()
machine_password=re.sub('\n','',pwdLine)

machine_uid=pwd.getpwnam('%s$' % (baseConfig['hostname']))[2]
old_uid=os.getuid()
os.setuid(machine_uid)

child = spawn( lpadminexec, args )

i=0
timeout=60
attempt=0
rc = 0

def show_child_before_message(child):
	""" Method shows only lpadmin error/info message that comes only with "lpadmin: """
	for stdout_line in child.before.splitlines():
		if "lpadmin: " in stdout_line:
			print stdout_line.strip()


def enableaccept(command, groupname, timeout, machine_password):
	""" Method for enabling and accept classes """
	i = 0
	child = spawn(command, [groupname])
	#print child
	while not i == 3:
		i = child.expect(['%s\.%s.*\?' %(baseConfig['hostname'],baseConfig['domainname']), '%s.*\?' % baseConfig['hostname'], 'localhost.*\?', EOF], timeout=timeout)
		#print command, " %s" % i
		if i in [0,1,2]:
			child.sendline(machine_password)

	if child.isalive():
		child.close()

	if child.exitstatus and child.exitstatus != 0:
		print 'The command "%s %s" returned %d' % (command, groupname, child.exitstatus)
		sys.exit(child.exitstatus)


while not i == 3:
	i = child.expect(['%s\.%s.*\?' %(baseConfig['hostname'],baseConfig['domainname']), '%s.*\?' % baseConfig['hostname'], 'localhost.*\?', EOF], timeout=timeout)
	if i in [0,1,2]:
		show_child_before_message(child)
		child.sendline(machine_password)
		attempt += 1

	if attempt > 3:
		print 'Failed to create the printer with the following command: '
		print '  %s %s' % (lpadminexec, ' '.join(args))
		print 'Please check the machine account or the PAM configuration.'
		sys.exit(1)


show_child_before_message(child)

if child.isalive():
	child.close()

if child.exitstatus and child.exitstatus != 0:
	print 'The command "%s %s" returned %d' % (lpadminexec, ' '.join(args) , child.exitstatus)
	sys.exit(child.exitstatus)

# check for several classes
if '-c' in args:
	i=0
	for arg in args:
		if arg == '-c':
			#print "arg: ", args[i+1]
			enableaccept(enableexec, args[i+1], timeout, machine_password)
			enableaccept(acceptexec, args[i+1], timeout, machine_password)
		i += 1

sys.exit(0)
