#!/bin/sh

# Copyright (C) 2005-2006 Junjiro Okajima
#
# This program, aufs is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

# $Id: unionctl,v 1.6 2006/08/07 14:52:33 sfjro Exp $

# simple script for controling aufs.
# compatible with unionctl(8) of unionfs(5).
# if you use "mount -o remount" to add/del/mod branches,
# this scirpt is unnecessary.

PATH=/usr/bin:/usr/sbin:/bin:/sbin
export PATH
eecho() { echo $@ 1>&2; }

########################################

test $# -lt 2 && eecho bad arg $@ && exit 1
f=/proc/mounts
test ! -f $f && eecho $f is neccessary && exit 1

set -e
#set -x; echo $@
cd $1
mntpnt=$PWD
cd $OLDPWD
action=$2
shift 2

dirs=`grep ' '${mntpnt}' unionfs' $f |
cut -d' ' -f4 |
sed -e 's/.*dirs=\([^,]*\).*/\1/' -e 's/=[^:]*:*/ /g'`
#echo ${dirs}; exit
test "$dirs" = "" && eecho no such mntpnt $mntpnt && exit 1

find_bindex() # dir
{
	echo $1 | grep -q '^[0-9]*$' && echo $1 && return 0
	local i n
	n=0
	for i in ${dirs}
	do
		test ${i} = ${1} && echo $n && return 0
		n=`expr $n + 1`
	done
	eecho no such branch $1
	echo -2
	return 1
}

Remount() #options...
{
	local f=/proc/sys/vm/drop_caches
	# if you feel remount is slow, try uncommenting this line
	#test -w $f && echo 2 > $f
	#sleep 1; /tmp/lktr_exec /bin/mount -o remount,$@ ${mntpnt}
	exec mount -o remount,$@ ${mntpnt}
}

do_add()
{
	local bindex perm br
	bindex=0
	perm=rw # unionfs default
	br=
	while [ "$br" = "" ]
	do
		case $1 in
		--before)	bindex=`find_bindex $2`
				bindex=`expr $bindex - 1`
				;;
		--after)	bindex=`find_bindex $2`
				bindex=`expr $bindex + 1`
				;;
		--mode)		perm=$2;;
		--*)		eecho unkown option $@; return 1;;
		*)		br=$1
		esac
		test "$br" = "" && shift 2 || :
	done

	test $# -ne 1 && eecho bad arg $@ && return 1
	br=$1
	test $bindex -lt 0 && bindex=0 || :
	Remount add:${bindex}:${br}=${perm}
}

do_del()
{
	test $# -ne 1 && eecho bad arg $@ && return 1
	Remount del:${1}
}

do_mod()
{
	test $# -ne 2 && eecho bad arg $@ && return 1
	Remount mod:${1}=${2}
}

case $action in
--add)		do_add $@;;
--remove)	do_del $@;;
--mode)		do_mod $@;;
--list|--query)	eecho unsupported action $action;;
*)		eecho unkown action $action;;
esac
