# script to generate initial password for users and add samba credentials
#
# Copyright (C) 2007  GONICUS GmbH  info@GONICUS.de
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

#!/bin/sh

if [ $# -ne 1 ]; then
	echo "Usage: $(basename $0) usermappping";
	exit 1
fi

[ -f pw-list.ldif ] && rm pw-list.ldif

cat $1 | while read ncp userid; do

	if [ -z "$userid" ]; then
		echo "FEHLER bei ncp='$ncp' userid='$userid'"
		echo "  userid leer!"
		exit 1
	fi

	cn=$(getent passwd $userid | cut -d: -f5)
	pw=$(apg -n 1 -a 0 -M NCL)

	if [ -z "$cn" ]; then
		echo "FEHLER: cn nicht auffindbar für ncp='$ncp' userid='$userid'"
		exit 2
	fi

	# Ausgabe csv
	echo "$cn;$userid;$pw"

	# (Test) Ausgabe ldif
	hash=$(perl -MCrypt::SmbHash -e "print join(q[:], ntlmgen ('$pw')), $/;")
	lm=$(echo -n $hash | cut -d: -f1)
	nt=$(echo -n $hash | cut -d: -f2)
	id=$(id -u $userid 2> /dev/null)
	[ $? -ne 0 ] && continue
	id=$(( $id * 2 + 3000 ))

	# DN holen
	dn=$(ldapsearch -x -LLL uid=$userid dn)

	(
	# Schon ein Samba Account?
	if ldapsearch -x -LLL uid=$userid objectClass | grep -qi sambaSamAccount; then
		cat <<-EOF
		$dn
		changetype: modify
		replace: sambaLMPassword
		sambaLMPassword: $lm
		-
		replace: sambaNTPassword
		sambaNTPassword: $nt

		EOF
	else
		if ldapsearch -x -LLL uid=$userid sambaLMPassword | grep -qi sambaLMPassword; then
			mode="replace"
		else
			mode="add"
		fi
		cat <<-EOF
		$dn
		changetype: modify
		replace: objectClass
		$(ldapsearch -x -LLL uid=$userid objectClass | grep '^objectClass:')
		objectClass: sambaSamAccount
		-
		$mode: sambaLMPassword
		sambaLMPassword: $lm
		-
		$mode: sambaNTPassword
		sambaNTPassword: $nt
		-
		add: sambaSID
		sambaSID: S-1-5-21-2667935563-2357875570-3979385440-$id
		-
		add: sambaAcctFlags
		sambaAcctFlags: [UX          ]
		-
		add: sambaDomainName
		sambaDomainName: KULREF

		EOF
	fi
	) | ldapmodify -x -D "cn=manager,ou=incoming,ou=Kulturreferat,o=Landeshauptstadt München,c=de" -wfoo 1>&2

	# Gruppenzugehörigkeiten erfüllen
	net rpc -Uadmin%password -S kulpdc group ADDMEM "Domain Users" $userid
	net rpc -Uadmin%password -S kulpdc group ADDMEM "Gruppe_1" $userid
	net rpc -Uadmin%password -S kulpdc group ADDMEM "Gruppe_2" $userid
done
