#!/bin/bash

set -e

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

changed=0
c_mounts=""
FSTAB=/etc/fstab

check_and_fix_opts() {
	opt="$1"
	# make sure homes are mounted nosuid. Not perfect but should work
	# Based on STIG check.
	# caveat: if the fstab is different than the options in kernel, this wont work properly
	home_mounts=$(for X in `egrep "^[^:]{1,}:x:[1-4][0-9]{3}:" /etc/passwd | cut -d: -f6`; do findmnt -nkT $X; done | sort -r| egrep -v '^/\s+' | grep -wv $opt | awk '{print $1}')
	# Look for nfs
	nfs_mounts=`grep nfs $FSTAB | grep -wv $opt | awk '{print $2}'`

	mounts="$home_mounts $nfs_mounts"
	if [ "x$mounts" != "x " ]; then
		for mnt in $mounts; do
			if [ $test_mode -eq 0 ]; then
				sed -r -e "s!^(\S+)\s+$mnt\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\$!\1\t$mnt\t\2\t\3,$opt\t\4\t\5!g" -i $FSTAB
				if grep -qw $mnt /proc/mounts; then
					mount -o remount,$opt $mnt
				fi
			fi
			if [ "x$c_mounts" == "x" ]; then
				c_mounts="\"$opt:$mnt\""
			else
				c_mounts="$c_mounts,\"$opt:$mnt\""
			fi
		done
	fi
}

check_and_fix_opts nosuid
check_and_fix_opts noexec

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

