#!/bin/bash


astramode=`/usr/sbin/astra-modeswitch get 2> /dev/null`;

case "$astramode" in
	0)     	exit 0;;
	1)     	sysmaxlbl=`pdp-ls -Mdn / | awk '{ print $5 }' | awk -F":" '{ print "0:"$2":0" }'`;;
	2) 	sysmaxlbl=`pdp-ls -Mdn / | awk '{ print $5 }' | awk -F":" '{ print $1":"$2":"$3 }'`;;
	*)	echo "unknown astramode"; exit 1;;
esac

function split_path() {
	local IFS='/'
	set -f
	path_arr=( $@ )
	set +f
	path_len=$((${#path_arr[@]} - 1))
}

function join_path() {
	for i in $(seq 1 $1); do
		echo -n "/${path_arr[$i]}"
	done
	echo ""
}

function pdpl_file_join() {
	label=$1
	fname=$2

	if pdpl-file "$label" "$fname"; then return 0; fi

	oldlbl=`pdp-ls -Mdn $fname | tr -s " " | cut -d " " -f5`
	newlbl=""
	for field in 1 2 3; do
		a=$(echo $oldlbl | cut -d ":" -f $field)
		b=$(echo $label | cut -d ":" -f $field)
		c=$(($a | $b))
		newlbl="${newlbl}${c}:"
	done
	flags=$(echo $label | cut -d ":" -f 4)
	newlbl="${newlbl}${flags}"
	pdpl-file "$newlbl" "$fname"
	return $?
}

function pdpl_file_smart() {
	label=$1
	orig_path=$2

	split_path $orig_path

	for i in $(seq $path_len -1 0); do
		if [ $i -eq 0 ]; then return 1; fi
		path=$(join_path $i)
		if pdpl_file_join "$label" "$path" 2> /dev/null; then break; fi
	done

	if [ $i -eq $path_len ]; then return 0; fi

	for j in $(seq $i $path_len); do
		path=$(join_path $j)
		if ! pdpl_file_join "$label" "$path"; then return 1; fi
	done
}

# for libvirt
LIBVIRT_DIRS="\
/var/lib/polkit-1/localauthority \
/var/lib/libvirt/nvram \
/var/lib/libvirt/images \
/var/lib/libvirt/runimages \
/var/lib/libvirt/swtpm \
/var/lib/libvirt/hash \
/var/lib/libvirt/hash/config \
/var/lib/libvirt/qemu/   \
/var/run/libvirt/qemu/channel/ \
/var/lib/libvirt/qemu/save/ \
/var/lib/libvirt/qemu/snapshot/ \
/var/lib/libvirt/qemu/nvram/ \
/var/lib/libvirt/qemu/ram/ \
/var/lib/libvirt/qemu/dump/ \
/var/run/libvirt/qemu/   \
/var/run/libvirt/qemu/swtpm \
"

for dir in ${LIBVIRT_DIRS}; do
	[ -e "${dir}" ] || mkdir -p "${dir}"
	pdpl_file_smart "$sysmaxlbl:CCNRA" "${dir}"
	if [ "$?" -ne 0 ]; then
		echo "can't set label for ${dir}"
	fi
done

if [ -e /dev/kvm ]; then
	pdpl-file 0:0:0:ehole /dev/kvm
fi

if [ -e /dev/vfio ]; then
	pdpl_file_smart "$sysmaxlbl:CCNRA" /dev/vfio
fi

if [ -e /dev/bus ]; then
	pdpl_file_smart "$sysmaxlbl:CCNRA" /dev/bus
fi
