#!/bin/bash
#
# __copy1__
# __copy2__
#
CMD=$(basename $0)

set -u

usage()
{
	echo "usage: $CMD [user]" >&2
	exit 127
}

# (MAIN)

realuid=$(id -u)
realuser=$(id -un)
user=$realuser


[ $# -gt 1 ] && usage

[ $# == 1 ] && {
	# is a valid user?
	user=$1
}
uid=$(id -u $user 2>/dev/null)
[ "$uid" == "" ] && {
	echo "invalid user '$user'" >&2
	exit 1
}

# is ldap user?
#
ldap_dn=
ldap_uid=
[ -f /etc/ldap.conf ] && {
	ldapquery="(&(objectclass=posixAccount)(objectclass=shadowAccount)(uid=$user))"
	ldapentry=$(ldapsearch -x "$ldapquery" dn uid 2>/dev/null)
	ldap_dn=$(echo "$ldapentry" | grep '^dn: ' | sed -e 's/^dn: //')
	ldap_uid=$(echo "$ldapentry" | grep '^uid: ' | sed -e 's/^uid: //')
}

if [ "$ldap_dn" != "" ]
then
	# to change ldap password we use smbldap-tools, user should be able
	# to change only own password, but smbldap-passwd always run
	# with root credential, so we can have a big security hole here;
	#
	# if the user asked to change own password we exec a sudo helper that
	# runs smbldap-passwd on the user itself, otherwise we complain
	#
	echo "changing password for LDAP user $uid '$user' ($ldap_dn)"
	if [ "$user" == "$realuser" ]
	then
		cmd="ku-sudo-passwd"
		args=
	else
		cmd=smbldap-passwd
		args="$user"
		[ -r /etc/smbldap-tools/smbldap.conf ] || {
			echo "sorry, only root can do this" >&2
			echo "(file /etc/smbldap-tools/smbldap.conf not readable)" >&2
			exit 1
		}
	fi
else
	echo "changing password for UNIX user $uid '$user'"
	cmd=passwd
	args="$user"
fi

realcmd=$(which $cmd 2>/dev/null)
[ "$realcmd" == "" ] && {
	echo "can't find command '$cmd', abort" >&2
	exit 1
}

exec $realcmd $args
