#!/bin/bash
# barium helper scripts
# author: rosalinux.ru: betcher_
VARS="INDEX UNION CHANGES SPACE LINDEX"
if [ -f $(dirname $0)/lib ] ;  then
    . $(dirname $0)/lib
else 
    . $(which lib) || exit 1
fi

HLP() {
# aligned by tabs, do not align again
echo "
Usage:	$(basename $0) <dir>
	$(basename $0) -o <module_name> <list of sources>
	(where sources is a directories or another modules)

$(basename $0) keys:
	- o		- the name for module
	--mklist	- make the list of files/dirs for simle module
			  the list for contaners is always created
	--sqfs		- additional parameters for mksquashfs, --sqfs
			  must be last parameter in cmdline
"
	exit
}

UNIONFS=$(check_union)
sep='' ; SOURCES=''
#Разбор параметров cmdline
while [ -n "$1" ]
do
	case "$1" in
	"-o" | "--out-file" ) shift ; USEROUT="$1" ;;
	"-h" | "--help" ) HLP ; exit ;;
	"--mklist" ) MKLST=yes ;;
	"--sqfs" ) shift ; SQFSOPT="$@" ; break ;;
	*) SOURCES="${1}${sep}${SOURCES}"
				sep=' ';;
	esac
	shift
done

[ "$USEROUT" ] && modname="$USEROUT"
[ -z "$modname" -a  $(echo "$SOURCES" |wc -w) -eq 1 ] && modname="$(basename ${SOURCES}).${EXT}"
if [ -z "$modname" ] ; then
	echo "Please enter the name for module:"
	read modname
fi

[ -z "$SOURCES" ] && exitmsg "Sources list is empty, must be one or more" ${LINENO}
SOURCES_separated="$(echo $SOURCES | sed 's/ /,/g')"

for a in $(make_union $(prepare_layers LIST="$SOURCES_separated")); do
	echo $VARS |grep  -q "$(echo "$a" |cut  -f1 -d=)" &&  eval "$a"
done

if [ $(echo $SOURCES | wc -w) -eq 1 ] ;then
  NAME=$([ $(echo $SOURCES  |wc -w) -eq 1 ] && echo ${modname%.$EXT} |sed -e 's/_comma_/,/g' -e 's/_equal_/=/g' -e 's/_asterisk_/\*/g' -e 's/_hash_/\#/g' )
  [ $MKLST ] && make_list SOURCE="$UNION" DEST="$UNION" NAME="$NAME" #SPEC="$SPEC" DEPS="$DEPS" 
else
  bundles=$(ls_union $UNION hide_changes)
  for i in $bundles ;do
	  NAME="$(basename "${i%.$EXT}" |sed -e 's/_comma_/,/g' -e 's/_equal_/=/g' -e 's/_asterisk_/\*/g' -e 's/_hash_/\#/g')"    
	  make_list SOURCE="$i" DEST="$CHANGES" NAME="$NAME"
  done
fi

[ "$UNION" ] && mksquashfs "$UNION" "$modname" ${SQFSOPT}  -noappend

destroy_union $INDEX
destroy_layers $LINDEX

