#!/bin/bash
export init_file="/etc/iac/iac_labels.iac"
export iac_T_label="trusted.iac"
export iac_label="security.iac"

if [ $# != 1 ]; then
	echo "set/unset is required"
	exit -1
fi

if [ ! -f "$init_file" ]; then
	"$init_file is not found."
	exit -1
fi

if ! which attr &>/dev/null; then
	echo "Command 'attr' not found, exit."
	exit -1
fi

function label_set()
{
	while read file label ; do
		if echo "$file" "$label" | grep -q "^#" ; then
			continue;
		fi
		if [ -z "$file" -o -z "$label" ] ; then
			continue;
		fi

		if [ x$label == 'xT' ] && \
			! getfattr -dn "trusted.iac" --only-values "$file" 2>/dev/null | grep -qw "\<on\>" ; then
			setfattr -hn $iac_T_label -v "on" "$file" 2>/dev/null;
			setfattr -hn $iac_label -v "1" "$file" 2>/dev/null;
		fi
	done <$init_file
}

function label_unset()
{
    while read file label ; do
        if echo "$file" "$label" | grep -q "#" ; then
            continue;
        fi
        if [ -z "${file}" -o -z "${label}" ] ; then
            continue;
		fi
        setfattr -hx $iac_T_label "$file" 2>/dev/null
        setfattr -hx $iac_label "$file" 2>/dev/null
    done <$init_file
}

if [ $1 == 'unset' ]; then
	if cat /proc/self/attr/iac > /dev/null 2>&1 ; then
		if grep -Ewq "(\<1\>|\<2\>)" /sys/module/iac/parameters/iac_mode; then
			echo "IAC is still runing, and can not unset IAC labels. It is recommended not to do so."
			exit 0
		fi
	fi
	echo "unset iac label: ongoing; this might take a long time ..."
	label_unset  && echo "unset iac label: done"
elif [ $1 == 'set' ]; then
	echo "set iac label: ongoing; this might take a long time ..."
	label_set && echo "set iac label: done" || echo "set iac label: failed"
else
	echo "parameter(set/unset) is required."
fi
