#!/bin/bash

if [ "$1" = '' ]; then
	echo "Syntax: $0 <username> <password>" > /dev/stderr
	exit 2
fi

if [ "$2" = '' ]; then
	echo "Syntax: $0 <username> <password>" > /dev/stderr
	exit 2
fi

USER="$1"
PASS="$2"

# see: https://unix.stackexchange.com/questions/197628/a-little-help-passwd-status-on-linux
PWD_STATUS=$( passwd -q -S "$USER" 2>/dev/null )

if [ $? -ne 0 ]; then
	echo "Error: User $USER does not exist" > /dev/stderr
	exit 1
fi

PWD_STATUS=$( echo "$PWD_STATUS" | cut -d ' ' -f 2 )

if [ "$PWD_STATUS" == "P" ]; then
	echo -e "$PASS\n$PASS" | passwd -q "$USER" > /dev/null 2>&1
	exit $?
elif [ "$PWD_STATUS" == "L" ]; then
	echo "Error: Password for user $USER cannot be changed. (User account is locked)" > /dev/stderr
	exit 1
elif [ "$PWD_STATUS" == "NP" ]; then
	echo "Error: Password for user $USER cannot be changed. (User has no password yet)" > /dev/stderr
	exit 1
else
	echo "Error: Password for user $USER cannot be changed. (Password status is $PWD_STATUS)" > /dev/stderr
	exit 1
fi
