#!/bin/bash

set -e

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

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

OIFS="$IFS"
IFS=$'\n'
filelist=""
for f in $({{ filter }}); do
	stats=`stat --printf="%#a:%U:%G:%F\n" "$f"`
	fmode=`echo $stats| cut -d: -f1`
	fowner=`echo $stats| cut -d: -f2`
	fgroup=`echo $stats| cut -d: -f3`
	ftype=`echo $stats| cut -d: -f4`

	if [ "$ftype" != "directory" -a "$ftype" != "regular file" ]; then
		continue
	fi

	if [ "x$skip_list" != "x" -a "$f" != "/usr/bin/[" ]; then
		if echo "$skip_list" | grep -qw "$f"; then
			continue
		fi
	fi

	changes=""

	# world writable
	if [ $((fmode & 2)) -ne 0 ]; then
		if [ $test_mode -eq 0 ]; then
			chmod o-w "$f"
		fi
		changes="\"world-writable\""
	fi
	# group writable
	if [ $((fmode & 16)) -ne 0 ]; then
		if [ $test_mode -eq 0 ]; then
			chmod g-w "$f"
		fi
		if [ "x$changes" == "x" ]; then
			changes="\"group-writable\""
		else
			changes="$changes,\"group-writable\""
		fi
	fi
	# owner not root
	if [ "$fowner" != "root" ]; then
		if [ $test_mode -eq 0 ]; then
			chown root "$f"
		fi
		if [ "x$changes" == "x" ]; then
			changes="\"root-owner\""
		else
			changes="$changes,\"root-owner\""
		fi
	fi
	# group not root
	if [ "$fgroup" != "root" ]; then
		if [ $test_mode -eq 0 ]; then
			chgrp root "$f"
		fi
		if [ "x$changes" == "x" ]; then
			changes="\"root-group\""
		else
			changes="$changes,\"root-group\""
		fi
	fi
	if [ "x$changes" == "x" ]; then
		continue
	fi
        entry="{\"$f\": [$changes]}"
	if [ "x$filelist" == "x" ]; then
		filelist="$entry"
	else
		filelist="$filelist,$entry"
	fi
done

if [ "x$filelist" == "x" ]; then
	echo "{\"changed\": false}"
else
	echo "{\"changed\": true, \"files\": [$filelist]}"
fi
IFS="$OIFS"
