#!/bin/bash

set -e

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

test_mode=0
if [ $# -gt 1 ]; then
	test_mode=1
fi

skip_list="{{ config.skip_list | join(" ") }}"
cmd_out=""

check_min() {
	list=`cat /etc/shadow | cut -d ':' -f1,4 | grep -v ":$" || /bin/true`
	if [ "x$list" == "x" ]; then
		echo "{\"changed\": false}"
		return
	fi
	userlist=""
	for u in $list; do
		username="${u/:*}"
		age="${u/*:}"
		if [ $age -ne 0 ]; then
			continue
		fi
		if [ "$username" == "nobody" ]; then
			continue
		fi
		userid="`id -u $username`"
		if [ $userid -lt {{ min_uid }} ]; then
			continue
		fi
		if [ "x$skip_list" != "x" ]; then
			if echo "$skip_list" | grep -qw "$username"; then
				continue
			fi
		fi
		if [ $test_mode -eq 0 ]; then
			cmd_out=`passwd -n {{ config.min_days }} $username 2>&1`
		fi
		if [ "x$userlist" == "x" ]; then
			userlist="\"$username\""
		else
			userlist="$userlist,\"$username\""
		fi
	done
	if [ "x$userlist" == "x" ]; then
		echo "{\"changed\": false}"
		return
	fi
	echo "{\"changed\": true, \"users\": [$userlist], \"console\": \"$cmd_out\"}"
}

check_max() {
	list=`cat /etc/shadow | cut -d':' -f1,5 | grep -v ":$" || /bin/true`
	if [ "x$list" == "x" ]; then
		echo "{\"changed\": false}"
		return
	fi
	userlist=""
	for u in $list; do
		username="${u/:*}"
		age="${u/*:}"
		if [ $age -le {{ config.max_days }} ]; then
			continue
		fi
		if [ "$username" == "nobody" ]; then
			continue
		fi
		userid="`id -u $username`"
		if [ $userid -lt {{ min_uid }} ]; then
			continue
		fi
		if [ "x$skip_list" != "x" ]; then
			if echo "$skip_list" | grep -qw "$username"; then
				continue
			fi
		fi
		if [ $test_mode -eq 0 ]; then
			cmd_out=`passwd -x {{ config.max_days }} $username 2>&1`
		fi
		if [ "x$userlist" == "x" ]; then
			userlist="\"$username\""
		else
			userlist="$userlist,\"$username\""
		fi
	done
	if [ "x$userlist" == "x" ]; then
		echo "{\"changed\": false}"
		return
	fi
	echo "{\"changed\": true, \"users\": [$userlist], \"console\": \"$cmd_out\"}"
}

case "$1" in
	min)
		check_min
		;;
	max)
		check_max
		;;
	*)
		exit 1
		;;
esac
