#!/bin/sh
# @vasm : vpasswd
# @level: root
# @description: change user or root password
# 
# (c) Eko M. Budi, 2003
# (c) Vector Linux, 2003
#
# Released under GNU GPL

if [ ! "$VASM_FUNCTIONS" ]; then
  . /sbin/vasm-functions
fi

check_root

pfile="/etc/passwd"

USERNAME="$1"

# If USERNAME is defined, just ask password
if [ "$USERNAME" ] && [ "`grep -e "^${USERNAME}:" $pfile`" ]; then
  while [ 1 ]; do
    passwordbox "New password for $USERNAME" "CHANGE PASSWORD"
    USERPASS1="`cat $freply`"
    clean_tmp

    passwordbox "Re-enter new password" "CHANGE PASSWORD"
    USERPASS2="`cat $freply`"
    clean_tmp
  
    if [ ! "$USERPASS1" = "$USERPASS2" ]; then
      msgbox "Sorry. The password did not match. Please repeat" "ERROR"
      continue
    fi
    /sbin/passwdx $USERNAME $USERPASS1 > /dev/null
    if [ $? = 0 ]; then 
      infobox "Changing password DONE "
      sleep 1
      clean_exit
    else
      msgbox "Changing password FAILED. Lets repeat"
    fi  
  done
fi

#############################################
# No USER NAME, more complex

function list_user () {
  DIMENSION="12 50 8"
  TITLE="CHANGE PASSWORD"
  TEXT="\nThis list shows the the first 100 users with UID>=500\n\n
  Select the user then press OK\n
  or select EDIT if you can't find it in the list"

echo '$DCMD --backtitle "$BACKTITLE" --title "$TITLE" --menu "$TEXT" 20 50 10 \' > $fmenu
echo '"EDIT" "Enter name manually" \' >> $fmenu
## List the user, but only for the first 40
awk -F: '{ if ($3>=500) {print $0; num++}; if (num>=100) exit 0}' $pfile | sort | while read LINE; do
   N1=`echo $LINE | cut -d ':' -f 1`
   N2=`echo $LINE | cut -d ':' -f 5 | cut -d ',' -f 1`
   echo "$N1" "\"$N2 \" \\" >> $fmenu
done
echo '2> $freply' >> $fmenu

#cat $fmenu

source $fmenu

#cat $freply

  if [ $? = 1 -o $? = 255 ]; then
    exit 1
  fi
}

###############################################################
# MAIN
while [ 1 ]; do
    list_user
    USERNAME=`cat $freply`
    if [ "$USERNAME" = "EDIT" ]; then
       USERNAME=""
       while [ -z "$USERNAME" ]; do
          inputbox "Enter user name" "CHANGE PASSWORD"
          USERNAME="`cat $freply`"
       done
       # check user existence
       if [ "`grep -e "^${USERNAME}:" $pfile`" ]; then
           break
       fi
       msgbox "User '$USERNAME' does not exists; please choose another one"
    fi
done
# call self
$0 $USERNAME 

clean_exit

