#!/bin/bash
# barium helper scripts
# author: rosalinux.ru: betcher_
ROOT=/
if [ -f $(dirname $0)/b-lib ] ;  then
    . $(dirname $0)/b-lib
else 
    . $(which b-lib) || exit 1
fi    

HLP () {
	echo -e "$(basename $0) утилита для контроля слоев overlayfs/aufs" 
	echo "Использование:" 
	echo "	$(basename $0)			- список слоев основной rootfs OS barium"
	echo "	$(basename $0) 2 			- список слоев  созданной b-lib make_ovl/make_aufs с индексом 2"
	echo "	$(basename $0) --raw		- список в формате удобном для парсинга"
	echo "	$(basename $0) --raw  '"'$n $source'"'	- только нужные значения"
	echo "Доступные значения:"
	echo '  $n - layer number'
	echo '  $source - source of layer (module,image,dir,etc)'
	echo '  $bname_source - source base name'
	echo '  $dname_source - source dir name'
	echo '  $bundle - source mount point' 
	echo '  $bname_bundle - bundle base name'
    echo '  $dname_bundle - bundle dir name'
    exit 1
}

addZeros() {
	len=$((3 - $(echo $1 |wc -c)))
	for a in $(seq $len) ; do
		echo -n 0
	done
	echo $1
}

header() {
	printf %3s "N "; printf %-65s "Bundle Mount point " ; printf "Layer perms\n"
	printf %-68s "   Source " ;  printf  "Bundle perms\n\n"
}

listing() {
layer_perm=rw
n=0

[ "$hidetop" ] && bundles=$(ls_union $ROOT hidetop ) || bundles=$(ls_union $ROOT)
[ "$reverse" ] && bundles=$(echo "$bundles" |tac)

for a in $bundles ; do
	bundle=$a
    bundle_perm=$( [ -w $bundle ] && echo rw || echo ro )
    loop=$(findmnt  $bundle -o SOURCE | tail -n1  | tr -d '],['  ) 
    [ $loop ] || loop=$(df $bundle |tail -n1 | awk '{print $1}')
    source=$(losetup |grep  "$loop " |awk '{print $6}') 
    [ $source ] || source=$loop
    if ! [ "$raw" ] ; then 
      printf %3s "$(addZeros $n) "; 
      
      printf %-65s "$bundle " ; printf %b "${color_default}"
      [ "$layer_perm" = "rw" ] && printf %b "${color_green}" ; 
      printf "$layer_perm\n" ; printf %b "${color_default}"
      
      [ "$source" = "tmpfs" ] && printf %b "${color_blue}" ;
      echo "$source" |grep -q "^/dev/.*$"  && printf %b "${color_yellow}" ;
      
      printf %-68s "   $source " ;  printf %b "${color_default}"
      [ "$bundle_perm" = "rw" ] && printf %b "${color_green}" ;
      printf  "$bundle_perm\n" ; printf %b "${color_default}"
      echo ''
    else
	  dname_source=$(dirname $source) ; bname_source=$(basename $source)
      dname_bundle=$(dirname $bundle) ; bname_bundle=$(basename $bundle)
      eval echo "$returnMe"
    fi
    n=$(( n + 1 )) ; layer_perm=""
done    
}    

if  echo $@ |grep -q "\-\-raw" ; then
	raw='yes'
	returnMe="$(echo $@ |sed 's/^.*\-*raw//')"
	[ "$returnMe" ] || returnMe='$n $bundle $layer_perm  $source $bundle_perm'
fi
echo $@ |grep -q "\-\-reverse" && reverse=yes 
echo $@ |grep -q "\-\-hidetop" && hidetop=yes 
if [ $1 ] ; then
	[ "$1" == '--help' -o "$1" == '-h' ] && HLP
	[ -d "$1" ] && ROOT=$1
	expr "$1" + 1 > /dev/null 2>&1 && ROOT=$1
fi
listing 
