#!/bin/sh -e

. alterator-kdc-princ-functions
. alterator-openldap-functions

# Read default configuration
set_ldap_config

[ -n "$DN_CONF" ] || fatal "DN_CONF not set"

[ "$#" -ne 0 -a "$#" -le 3 ] || fatal "more arguments required. See --help for details"
user="$1"; shift
pw="$1"

# Parse arguments
case "$user" in
    "--version")
        get_ldap_version
        exit
        ;;
    -h|--help)
        cat <<EOF
Usage: 

    $0 <user> [<new_passwd>]

Arguments:

    user        LDAP user name
    password    New password. If omitted password will be read from stdin.
    -h, --help  show this help
    --version   show version

EOF
        exit
        ;;
esac

# If password does not set in command line, read it from stdin
[ -z "$pw" ] && read -es pw

# setting ldap-password
samba_pw="$(mkntpasswd $pw)"
lm=${samba_pw%%:*}
nt=${samba_pw##*:}

lp="$(slappasswd -h '{CRYPT}' -c '$2a$05$%.24s' ${pw:+-s "$pw"})"

[ -n "$lp" ] || fatal "No password given"

# Check Kerberos is ready
if [ -n "$ENABLE_KRB" ]; then
    kdc_status=
	service krb5kdc status &>/dev/null || kdc_status="fail"

	# Change password in Kerberos database
    changepw "$user" "$pw" &>/dev/null || kdc_status="fail"

	# Error reaction
	[ "$kdc_status" = "fail" ] && fatal "unable to set password in Kerberos. Check krb5kdc service is running."
fi

#edit ldap
echo "dn: uid=$user,ou=People,$base
changetype: modify
replace: userPassword
userPassword:$lp
-
replace: sambaLMPassword
sambaLMPassword: $lm
-
replace: sambaNTPassword
sambaNTPassword: $nt" |
ldapmodify -D "$rootdn" $rootpw -x -H "ldap://${host:-127.0.0.1}" > /dev/null
