#!/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
}

if [ -n "$1" ]; then
	pdpl_file_smart "$sysmaxlbl:CCNRA" "$1"
else
	for stor in `ls /etc/libvirt/storage/*.xml`; do
		pool_type=$(xml2 < $stor  | grep /pool/@type= | sed 's/.*=//')
		if [[ $pool_type == "dir" ||  $pool_type == "netfs" ]]; then
			need_dir=$(xml2 < $stor  | grep /pool/target/path= | sed 's/.*=//')
			if [[ "$need_dir" =~ ^/home/ ]]; then continue; fi
			if [ -d "$need_dir" ]; then pdpl_file_smart "$sysmaxlbl:CCNRA" "$need_dir"; fi
		fi
	done
fi
