#!/bin/bash

admin_list="{{ admin_list | join(" ") }}"

set -e

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

user_list=""
for a in $admin_list; do
	changed=0
	while read -r line; do
		field=`echo $line | cut -d: -f1`
		value=`echo $line | cut -d: -f2`
		case "$field" in
			Password\ expires*)
				if [[ $value =~ never ]]; then
					continue
				fi
				if [ $test_mode -eq 0 ]; then
					chage -I -1 $a
				fi
				changed=1
				;;
			# https://www.stigviewer.com/stig/sles_12/2019-10-01/finding/V-77125
			# the check is talking of account expires but the fix is setting
			# only inactive (chage -I) but not of expire (chage -E)....
			# not sure what's right.
			Account*)
				if [[ $value =~ never ]]; then
					continue
				fi
				if [ $test_mode -eq 0 ]; then
					chage -E -1 $a
				fi
				changed=1
				;;
			Maximum*)
				if [[ $value =~ 99999 ]]; then
					continue
				fi
				if [ $test_mode -eq 0 ]; then
					chage -M 99999 $a
				fi
				changed=1
				;;
		esac
	done < <(chage -l $a)
	if [ $changed -eq 0 ]; then
		continue
	fi
	if [ "x$user_list" == "x" ]; then
		user_list="\"$a\""
	else
		user_list="$user_list,\"$a\""
	fi
done
if [ "x$user_list" == "x" ]; then
	echo "{\"changed\": false}"
else
	echo "{\"changed\": true, \"users\": [$user_list]}"
fi
