#!/bin/bash

set -e

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

userlist=""
for u in $(awk -F: '($3>={{ min_uid }})&&($7 !~ /nologin/){printf("%s:%s:%s\n",$1,$4,$6)}' /etc/passwd); do
	username=`echo $u | cut -d: -f1`
	home=`echo $u | cut -d: -f3`
	prim_gid=`echo $u | cut -d: -f2`
	changes=""
	if [ -d "$home" ]; then
		dir_mode=`stat --printf="%#a\n" "$home"`
		# Not sure if it's enough to ensure avoid less permissive rights than 0750
		if [ $((dir_mode & 7)) -ne 0 ]; then
			if [ $test_mode -eq 0 ]; then
				chmod o= "$home"
			fi
			changes="\"other_rights\""
		fi
		if [ $((dir_mode & 16)) -ne 0 ]; then
			if [ $test_mode -eq 0 ]; then
				chmod g-w "$home"
			fi
			if [ "x$changes" == "x" ]; then
				changes="\"group_rights\""
			else
				changes="$changes,\"group_rights\""
			fi
		fi

		dir_gid=`stat --printf="%#g\n" "$home"`
		if [ $dir_gid -ne $prim_gid ]; then
			if [ $test_mode -eq 0 ]; then
				chgrp $prim_gid "$home"
			fi
			if [ "x$changes" == "x" ]; then
				changes=\""primary_group\""
			else
				changes="$changes,\"primary_group\""
			fi
		fi
		if [ "x$changes" == "x" ]; then
			continue
		fi
	else
		if [ $test_mode -eq 0 ]; then
			uid=`id -u $username`
			cp -r /etc/skel "$home"
			chown -R $uid:$prim_gid "$home"
			chmod 0750 "$home"
		fi
		changes="\"new_home\""
	fi
        entry="{\"$username\": [$changes]}"
	if [ "x$userlist" == "x" ]; then
		userlist="$entry"
	else
		userlist="$userlist,$entry"
	fi
done

if [ "x$userlist" == "x" ]; then
	echo "{\"changed\": false}"
else
	echo "{\"changed\": true, \"users\": [$userlist]}"
fi

