#!/bin/bash
# barium helper scripts
# author: rosalinux.ru: betcher_

if [ -f $(dirname $0)/lib ] ;  then
    . $(dirname $0)/lib
else 
    . $(which lib) || exit 1
fi

LAYER=${SYSMNT}/layer-base/1

if [ ! "$1" ] || [ "$1" == '--help' ] || [ "$1" == '-h' ]; then
	echo "
Usage:	$(basename $0) <module> <layer number (default 1)>

	$(basename $0) module.xzm   - install module.xzm to ${SYSMNT}/layer-base/1/modules/
	$(basename $0) module.xzm 0 - install module.xzm to ${SYSMNT}/layer-base/0/modules/
"
	exit ${LINENO}
fi
module="$1"

[ $2 ] && LAYER=${SYSMNT}/layer-base/$2
[ -d $LAYER ] || exit ${LINENO}
DEVICE=$(grep -m1 " $LAYER " /proc/self/mountinfo | awk '{ print $10 }') 
MPOINT=$(findmnt -lnf $DEVICE -o TARGET)

if grep "$LAYER".*ro,  /proc/mounts  ; then
    mount -o remount,rw $lAYER
    REMOUNT_LAYER=yes
fi

if grep "$MPOINT".*ro,  /proc/mounts  ; then
    mount -o remount,rw $MPOINT
    REMOUNT_MPOINT=yes
fi

ret=$(getfile $module ${LAYER}/modules/$(basename $module))  

[ "$REMOUNT_MPOINT" ] && mount -o remount,ro "$MPOINT"
[ "$REMOUNT_LAYER"  ] && mount -o remount,ro "$lAYER"

file $ret |grep -qi 'squashfs' || exit ${LINENO}
ls $ret
