#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
#
# Univention Samba
#  set privilege for a user
#
# Copyright 2010-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/>.


from optparse import OptionParser
import univention.uldap
import tdb
import os.path
import sys


def setMachineAccountPrivilege( sambaSID ):
	tdbKey='PRIV_%s\x00' % (sambaSID )

	tdbFile=tdb.Tdb('/var/lib/samba/account_policy.tdb')
	tdbFile.lock_all()
	privs = tdbFile.get(tdbKey)
	if not privs:
		privs='\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

	privs='\x10'+privs[1:len(privs)]

	tdbFile[tdbKey]=privs

	tdbFile.unlock_all()

def username2sid( username ):
	lo=univention.uldap.getMachineConnection()
	res = lo.search(filter='(&(objectClass=sambaSamAccount)(uid=%s))' % username, attr=['sambaSID'])
	try:
		return res[0][1]['sambaSID'][0]
	except IndexError:
		return None
	except KeyError:
		return None


if __name__ == '__main__':
	parser = OptionParser( usage="usage: %prog [options]" )
	parser.add_option('-u', '--user',
			action='store', dest='username', default=None,
			help='Username to set given privilege for')
	parser.add_option('-p', '--privilege',
			action='store', dest='privilege', default=None,
			help='Set this privilege for given username. Currently supported privilege is SeMachineAccountPrivilege')

	(options, arguments) = parser.parse_args()

	if not os.path.exists('/var/lib/samba/account_policy.tdb'):
		print 'Error: /var/lib/samba/account_policy.tdb does not exist'
		sys.exit(1)

	if not options.username:
		parser.error("user is required")
		parser.usage()

	if not options.privilege:
		parser.error("privilege is required")
		parser.usage()

	if not options.privilege.lower() in [ 'semachineaccountprivilege' ]:
		print 'Error: The given privilege "%s" is not supported by this program' % (options.privilege)
		sys.exit(2)

	sambaSID = username2sid(options.username)
	if not sambaSID:
		print 'Error: Failed to convert "%s" to sambaSID.' % options.username
		sys.exit(3)

	if options.privilege.lower() == 'semachineaccountprivilege':
		setMachineAccountPrivilege(sambaSID)
	
