#!/usr/bin/expect -f
############################################################
#
# autopasswd
#
# Wrapper to make passwd be non-interactive.
# Usage: autopasswd username password
# Author: Phil Jones (phil@lfsp.org)
#
############################################################

#############
# Main code #
#############

# Check for correct usage.
if { $argc != 2 } {
   send_error "Usage: autopasswd \[user_name\] \[password\]\n"
   exit 1
}

# Red Hat systems have a bug in the passwd program.  The passwd
# program prompts for data entry before it is ready.  So we need
# to wait for a moment while the passwd program gets ready for
# input.  0.1 seconds should be enough but the passwd program does
# not make any guarantees.  You can change the set delay value to 0
# if you are using another distribution. 
set delay 0.1

# Get user's password from the second item on the command line.
set user [lindex $argv 0]
set password [lindex $argv 1]

# Spawn password command. 
# eg spawn 'passwd joe'.
spawn passwd $user

# Set password.
expect {
         "password:" { sleep $delay
                       send "$password\r"
                       sleep $delay
                       expect "password:" 
                       send "$password\r"
                       expect eof
                      }
          default     { send_error "autopasswd: User '$user' does not exist\n"
                        exit 1
                      }
}
