#!/bin/sh -e

##########################################################################
#   Script description:
#       
#   Arguments:
#       
#   Returns:
#       
#   History:
#   Date        Name        Modification
#   2015-01-31  Charlie &   Begin
##########################################################################

usage()
{
    cat << EOM

Usage: $0 username 'encrypted-password-entry'

Encrypted-password-entry should be an entire line from the file containing
encrypted passwords, such as /etc/master.passwd or /etc/shadow.

Single quotes are strongly recommended as encrypted passwords
may contain $ characters or other symbols that are interpreted by your
shell.

EOM
    exit 1
}


##########################################################################
#   Main
##########################################################################

if [ $# != 2 ]; then
    usage
fi

user_name=$1
pw="$2"
os_type=$(auto-ostype)

case $os_type in
FreeBSD)
    master_pw='/etc/master.passwd'
    ;;

RHEL)
    master_pw='/etc/shadow'
    ;;

*)
    auto-unsupported-os $0
    exit 1
    ;;

esac

# sed might trip on special characters in the encrypted password
awk -F : -v user_name=$user_name -v pw="$pw" ' {
    if ( $1 == user_name )
    {
	print pw;
    }
    else
    {
	print $0;
    }
}' $master_pw > $master_pw.tmp

if diff -q $master_pw $master_pw.tmp; then
    printf "No changes.\n"
    rm -f $master_pw.tmp
else
    case $os_type in
    FreeBSD)
	if [ ! -e $master_pw.bak ]; then
	    printf 'Backing up...\n'
	    cp $master_pw $master_pw.bak
	fi
	
	# Install updated master password file if it passes sanity test
	if pwd_mkdb -C $master_pw.tmp; then
	    printf 'Installing new pw...\n'
	    pwd_mkdb $master_pw.tmp
	fi
	;;
    RHEL)
	mv $master_pw.tmp $master_pw
	restorecon $master_pw
	;;
    *)
	;;
    esac
fi

