#!/bin/bash
#
CMD=$(basename "$0")
CMDVER="1.0"
CMDSTR="$CMD v$CMDVER (2020/06)"

set -e -u

usage()
{
	echo  "
== $CMDSTR == scans ldap shadowAccount entries for expired passwords ==

usage: $CMD
" >&2
	exit 1
}


ldapvalue()
{
	local var=$1
	grep "^$var:" | sed -e "s/^$var: //"
}



# (MAIN)

[ $# != 0 ] && usage


epoch=$(date --date '@0')
users=$(ku-ldapsearch objectClass=shadowAccount uid | ldapvalue 'uid')
now=$(date '+%s')
now=$(($now / 86400))

fmt="%-16s %-16s %6s %6s   %s\n"
printf "$fmt" "UID" "LAST CHANGE" "MAX" "AGE" "EXPIRED?"
echo

for uid in $users
do
	lastchange=$(ku-ldapsearch "uid=$uid" shadowLastChange | ldapvalue 'shadowLastChange')
	max=$(ku-ldapsearch "uid=$uid" shadowMax | ldapvalue 'shadowMax')

	renew=
	changedate=
	age=

	if [ "X$lastchange" != "X" ]
	then
		changedate=$(($lastchange * 86400))
		changedate=$(date --date "@$changedate" '+%Y-%d-%m')

		[ "X$max" != "X" -a "X$max" != "X0" ] && {
			age=$(($now - $lastchange))
			[ $age -gt $max ] && renew="yes"
		}
	else
		lastchange="NEVER"
		[ "X$max" != "X" -a "X$max" != "X0" ] && renew="yes"
	fi

	printf "$fmt" "$uid" "$changedate $lastchange" "$max" "$age" "$renew"
done

exit 0
