#!/bin/sh
#
#    Copyright (c) 2015 Brocade Communications Systems, Inc.
#    All rights reserved.
#
#    File name:   passwordhashchange 
#    Module name: fabos/src/utils/sys
#
#    This script is to check at login time if
#    the password hash type manual enforcement is disabled. If yes
#    and configured hash type != user passwd hash type, user is prompted.
#    for a passwd change.
#

PATH=/bin:/fabos/bin:/fabos/sbin:/fabos/libexec:/fabos/cliexec
ECHO=/bin/echo

username=`$ECHO $SWLOGNAME`
type=1

CONFIG_CMD="/fabos/cliexec/config"
PASSWORDHASHCONFIG=passwdcfg.hash
PASSWORDHASHMANUALCONFIG=passwdcfg.manualHashChange

FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
FABOS_SWITCHNO=0
hash=`$CONFIG_CMD get $PASSWORDHASHCONFIG 5`
manualhash=`$CONFIG_CMD get $PASSWORDHASHMANUALCONFIG 2`
FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP

if [ ! -z "$manualhash" ]; then
	if [ $manualhash -eq 0 ]; then
		if [ "$hash" == "md5" ]; then
			hash_magic="\$1$"	
		elif [ "$hash" == "sha256" ]; then
			hash_magic="\$5$"
		elif [ "$hash" == "sha512" ]; then
			hash_magic="\$6$"
		fi

		if [ $AUTH_TYPE -eq 1 ]; then
			exit 0
		fi

		userhashchk $type $username $hash_magic
		stat=$?
		#Invoke password change if hashes systemhash != userhash
		if [ $stat -eq 0 ] || [ $stat -eq 3 ]; then
			# No enforcement from "Crypt" to "MD5"
			if [ $stat -eq 3 ] && [ "$hash" == "md5" ]; then
				exit 0
			fi
			echo "Password hash enforcement: "
			/bin/passwd
			stat=$?
			if [ $stat -eq 0 ]; then
				passwd_notify -s $FABOS_SWITCHNO $username
				echo "Saving passwords to stable storage."
				/fabos/cliexec/config save /etc/passwd
				configsave_result=$?
				if [ $configsave_result -ne 0 ]; then
					echo "Failed to update passwords in stable storage"
				fi
				/fabos/cliexec/config save /etc/shadow
				configsave_result=$?
				if [ $configsave_result -ne 0 ]; then
					echo "Failed to update passwords in stable storage"
				else 
					echo "Passwords saved to stable storage successfully"
				fi
			else
				echo "Password change failed"
				exit 1
			fi
		elif [ $stat -eq 2 ]; then
			echo "Unable to retrieve user hash. Exiting.."
			exit 1
		fi
	fi
fi

