#! /bin/bash
# $Id: vrpm-preload,v 1.9 2004/05/05 19:37:19 ensc Exp $

# Copyright (C) 2003 Enrico Scholz <enrico.scholz@informatik.tu-chemnitz.de>
#  
# This program 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; version 2 of the License.
#  
# 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

set -e

: ${UTIL_VSERVER_VARS:=/usr/lib/util-vserver/util-vserver-vars}
test -e "$UTIL_VSERVER_VARS" || {
    echo $"Can not find util-vserver installation (the file '$UTIL_VSERVER_VARS' would be expected); aborting..." >&2
    exit 1
}
. "$UTIL_VSERVER_VARS"

function getCapFlags
{
    local ctx=$1
    
    if test "$ctx" && ! $_VSERVER_INFO - FEATURE migrate; then
	set -- $($_CHCONTEXT_COMPAT --xid 1 \
	    sh -c "cat /proc/[0-9]*/status | egrep '^(CapBset|s_context|ctxflags)'" | \
	    grep -B 1 -A 1 "^s_context: $ctx " | \
	    sed -e '1,3p;d' | awk '{ print $2 }')
    else
	set --
    fi

    if test "$3"; then
	RPM_FAKE_CAP=$[ ~0x$1 ]
	RPM_FAKE_FLAGS=$3
    else
	RPM_FAKE_CAP=$[ ~0xd40c04ff ]
	RPM_FAKE_FLAGS=4
    fi
}

lib=$_RPM_FAKE_SO

#scall_nr=$($_VSERVER_INFO  x SYSCALL_NEW_S_CONTEXT_NR  2>/dev/null)
#scall_rev=$($_VSERVER_INFO x SYSCALL_NEW_S_CONTEXT_REV 2>/dev/null)
vdir=$($_VSERVER_INFO "$CUR_VSERVER" VDIR)    || vdir="$CUR_VSERVER"
ctx=$($_VSERVER_INFO  "$CUR_VSERVER" CONTEXT) || ctx=

test -d "$vdir" || {
    echo $"Can not find chroot environment at '$vdir' for '$CUR_VSERVER'" >&2
    exit 1
}
for bin in `which rpm` /bin/rpm /usr/lib/rpm/rpm${RPM_FLAVOR:-i} ""; do
    ldd "$bin" &>/dev/null && break
done

test "$bin" || {
    echo $"No dynamically linked rpm binary found; exiting..."  >&2
    exit 1
}


getCapFlags "$ctx"

export RPM_FAKE_CAP RPM_FAKE_FLAGS

#RPM_FAKE_S_CONTEXT_REV=$scall_rev \
#RPM_FAKE_S_CONTEXT_NR=$scall_nr \
RPM_FAKE_CHROOT=$vdir \
RPM_FAKE_CTX=$ctx \
LD_PRELOAD=$lib${LD_PRELOAD:+:$LD_PRELOAD} \
exec $bin "$@"
