#!/bin/sh
# Script to install rrdtool inside apache chroot

RRD_CMD=${RRD_CMD:-/usr/local/bin/rrdtool}
PREFIX=${PREFIX:-/var/www}

if [ ! -x ${RRD_CMD} ]; then
    echo cannot find rrdtool - exiting
    exit 0
fi

FORMAT=`file ${RRD_CMD} 2>/dev/null`
if [ "${FORMAT}x" = x ]; then
    echo cannot determine executable format for rrdtool - exiting
    exit 0
fi

ELF=`echo ${FORMAT} | grep ELF`
if [ "${ELF}x" = x ]; then
    LIBS=`ldd "${RRD_CMD}" | sed -e '1d' -e '$d' -e 's/^.* \([^ ]*\)$/\1/g'`
else
    LIBS=`ldd "${RRD_CMD}" | sed -e '1,3d' -e '$d' -e 's/^.* \([^ ]*\)$/\1/g'`
fi

if [ "${LIBS}x" = x ]; then
    echo cannot determine library dependencies for ${RRD_CMD} - exiting
    exit 0
fi

cd ${PREFIX}
for lib in ${LIBS}; do
    libdir=`dirname ${lib}`
    mkdir -p ${PREFIX}${libdir}
    cp ${lib} ${PREFIX}${libdir}
done

mkdir -p bin usr/lib usr/libexec var/run usr/local/share/fonts etc/fonts
cp -f ${RRD_CMD} bin
cp -f /usr/libexec/ld.so usr/libexec
cp -f /bin/sh bin/sh
cp -f cp /usr/X11R6/lib/X11/fonts/TTF/DejaVuSansMono* usr/local/share/fonts
cat >etc/fonts/fonts.conf <<EOF
<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd">
<fontconfig>
	<description>Minimal configuration file</description>
	<dir>/usr/local/share/fonts</dir>
</fontconfig>
EOF
chown www:daemon var/run
cp /sbin/ldconfig bin/ldconfig
chroot -u www /var/www ldconfig /usr/lib /usr/local/lib /usr/X11R6/lib
rm bin/ldconfig
echo rrdtool, fonts and libs installed in apache root
