#!/bin/bash

set -e

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

list=`find / \( -path /.snapshots -o -path /sys -o -path /proc \) -prune -o -perm -002 -type d -exec stat --printf "%a\t%n\n" {} \;|grep -v '^1777'| awk '{print $2}'`

list2=`find /    -perm -002 -type d -exec stat --printf "%G:%n\n" {} \;`
valid_groups="{{ valid_groups | join(" ") }}"

for d in $list2; do
	group="`echo $d | cut -d: -f1`"
	dirname="`echo $d | cut -d: -f2`"
	if [ "x$valid_groups" != "x" ]; then
		if echo "$valid_groups" | grep -qw "$group"; then
			continue
		fi
	fi
	if [ "x$list" == "x" ]; then
		list="$dirname"
	else
		list="$list $dirname"
	fi
done

if [ "x$list" == "x" ]; then
	echo "{\"changed\": false}"
	exit 0
fi

dirlist=""
for dir in $list; do
	if [ $test_mode -eq 0 ]; then
		chmod 1777 $dir
		chgrp root $dir
	fi
	if [ "x$dirlist" == "x" ]; then
		dirlist="\"$dir\""
	else
		dirlist="$dirlist,\"$dir\""
	fi
done
echo "{\"changed\": true, \"directories\": [$dirlist]}"
