#!/bin/bash
# $Id$
# This script changes a users password in ldap - and if smbpasswd exists,
# also update samba password
# use at own risk

NEWPASSWD=

NAME=$1

if [ -z "$NAME" ] ; then 
  echo -e "usage: 
    $0 <username>"
  exit 2
fi

ldapdn() {
    filter="$1"
    ldapsearch -x "$filter" 2>/dev/null | perl -p0e 's/\n //g' | \| awk '/^dn: / {print $2}'
}

USERDN=$(ldapdn "(uid=$NAME)")

# Who do you want to change password of ? 
# only admin user are allow to change password of admin user
case "$NAME" in 
  admin)
    ENTRY=cn
    BINDUSER=$(ldapdn "(cn=admin)")
    ;;
  smbadmin)
    ENTRY=cn
    BINDUSER=$(ldapdn "(cn=admin)")
    NEWPASSWD=$(makepasswd)

    ;;
  *) ENTRY=uid 
     UID=$(id -un)
     BINDUSER=$(ldapdn "(uid=$UID)")
     ;;
esac

# Binding as admin only if you are root user,
# If you are root, you should know the admin password
test $(id -u) -eq 0 && BINDUSER=$(ldapdn "(cn=admin)")

if [ -z "$NEWPASSWD" ] ; then 
  # Make sure we have a new password (and we know what it is)
  read -p "Enter new password for user $NAME: " -s NEWPASSWD
  echo
  read -p "Reenter new password: " -s CHKPASSWD
  echo
  if [ "$CHKPASSWD" != "$NEWPASSWD" ] ; then 
    echo "Sorry, passwords don't match"
    exit 2
  fi
fi

# NOW Try to change the password
RESULT="$(ldappasswd -xZZW -s "$NEWPASSWD" -D $BINDUSER $ENTRY=$USERDN)"

if [ $? != 0 ] ; then
  echo "Could not change ldap passwd for user $NAME"
  echo "ldappasswd returned $RESULT"
  exit 2
fi

if [ ! -x /usr/bin/smbpasswd ] ; then 
  echo "Hmm, no smbpasswd, what kind of installation is this?"
  exit 0
fi

# Need to look at python-smbpasswd for this part

case "$NAME" in 
  admin) ;;
  smbadmin)
    # If we've changed the smbadmin PW, we also need to change the stored password
    /usr/bin/smbpasswd -w "$NEWPASSWD" >/dev/null
    ;;
  *) 
    # root should be able to use smbpasswd directly
    if [ $(id -u) -eq 0 ] ; then 
      echo -e "$NEWPASSWD\n$NEWPASSWD" | /usr/bin/smbpasswd -s "$NAME" >/dev/null
    else # admin users should be able to use sudo
      echo -e "$NEWPASSWD\n$NEWPASSWD" | sudo /usr/bin/smbpasswd -s "$NAME" >/dev/null
    fi
    ;;
esac
