#!/usr/bin/ksh
#
# Quick and dirty script to set a password
#
# Written by Thomas Sluyter (nagiosATkilalaDOTnl)
# By request of Unixerius, the Netherlands
# Last Modified: 11-01-2010
#
# Description:
#   Sometimes you're in a hurry and need to set a new, random password on an
# account. Don't feel your random banging the keyboard is random enough? Then
# use this script instead. 
#
# Usage: 
# ./boks_new_passwd.ksh [HGROUP|HOST]:USER
#
# Example: 
# ./boks_new_passwd.ksh SUN:thomas
# ./boks_new_passwd.ksh solaris2:root
#
# Limitations:
# * This script must be run on a BoKS master or replica.
# * This script must be run as root from the BoKS shell.
# * This script was tested with BoKS 6.0.x and 6.5.x.
#
# Output:
#   Three fields get echoed to stdout: the username, the password and the
# encrypted password string (should you ever need it).
#
# Other notes:
#   n.a.
#


### SETTING THINGS UP ###

PROGNAME=$(basename $0)
PATH="/usr/bin:/usr/sbin:/bin:/sbin:$PATH"

# Quick check to see if you're running as root with the BoKS shell

if [[ ( -z $BOKS_etc ) || ( -z $(id | grep "uid=0") ) ]]
then
        echo "ERROR: Script must be run as root, from the BoKS shell.\n"
        exit 1
fi


### REQUISITE COMMAND LINE STUFF ###

print_usage() {
	echo "Usage:"
	echo "$PROGNAME [HGROUP|HOST]:USER"
	echo "\nExamples:"
	echo "$PROGNAME SUN:thomas"
	echo "$PROGNAME solaris2:root\n"
	exit 1
}

if [[ ($# -eq 0) || (-z $(echo $1 | grep :))  ]]
then
	echo "\nERROR: Username not specified correctly.\n"
	print_usage
elif [[ ($($BOKS_sbin/lsbks -l $1 | wc -l) -lt 1) ]] 
then
	echo "\nERROR: Username does not exist.\n"
	print_usage
else
	USER="$1"	
fi


### DEFINING SUBROUTINES AND MAIN ROUTINE ###

GeneratePassword()
{
	echo "$RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM" |
	awk '{split("a b c d e f g h i j k m n p q r s t u w x y z 1 2 3 4 5 6 7 8 9 A B C D E F G H J K L M N P Q R S T U V W X Y Z",m)
	    a=$1%50+1;b=$2%50+1;c=$3%50+1;d=$4%50+1;e=$5%50+1;f=$6%50+1;g=$7%50+1;h=$8%50+1
	    print m[a]m[b]m[c]m[d]m[e]m[f]m[g]m[h]
	}' | read PASSWORD
}

GeneratePassword

$BOKS_lib/boksauth -c FUNC="change-psw" USER="$USER" OLDPSW="" NEWPSW="$PASSWORD" UID="0"
[[ $? -gt 0 ]] && echo "\n$USER\t$PASSWORD\tERROR: password change failed."

ENCPASSWORD=$($BOKS_sbin/lsbks -p -l $USER | awk -F: '{print $3}')

echo $USER $PASSWORD $ENCPASSWORD

