#!/bin/sh -e
# chroot-freenet - moves freenet into a chroot jail
# The jail is populated with the dependencies of freenet as well.
# !!! this script only works with kaffe 1.0.6 !!!
#
# It is permissible to run this script multiple times, if you always give the
# same CHROOT-JAIL parameter. In fact it is recommended to re-run it in regular
# intervals, so that files which were only copied (not hardlinked) can be
# updated with newer versions.

if [ $# -ne 1 ]; then
  echo "Usage: $0 CHROOT-JAIL"
  exit 1
fi

root="$1"

# lncp DESTINATION FILE...
# Tries a hardlink, and, if that fails, copies preserving status (cp -dp).
# Some file-util should do this.
lncp()
{
  local dest
  dest=$1
  shift
  [ -d $dest ] || mkdir $dest
  while [ $# -gt 0 ]; do
    if [ -d $1 ]; then
      [ -d $dest/$1 ] || mkdir $dest/$1
    else
      rm -f $dest/$1
      ln $1 $dest/$1 2>/dev/null || cp -dp $1 $dest/$1
    fi
    shift
  done
}

/etc/init.d/freenet-unstable stop
mkdir -p $root
cd $root

# init directory tree and needed devices
mkdir -p bin dev etc lib tmp usr/bin usr/lib usr/share/java var/lib var/log var/run
chown freenetu tmp var/run
cd dev
[ -e null ]    || mknod -m 666 null c 1 3
[ -e tty ]     || mknod -m 666 tty c 5 0
[ -e urandom ] || mknod -m 444 urandom c 1 9
cd ..

echo 'root:x:0:0:root:/root:/bin/sh' > etc/passwd
grep '^freenetu:' /etc/passwd >> etc/passwd

# these are all directories belonging to our package; move and symlink them
for d in etc var/lib var/log; do
  if [ ! -L /$d/freenet-unstable ]; then
    mv /$d/freenet-unstable $d
    ln -s $root/$d/freenet-unstable /$d
  fi
done

# for single files, symlinking won't work; so divert this
for f in `find /usr/share/java -name freenet-unstable-\*.jar -type f -print`; do
  mv $f $root$f
  dpkg-divert --local --divert $root$f $f
  ln -s $root$f $f
done

# was used in previous versions, no longer needed
rm -f $root/usr/share/java/servlet-2.2.jar

for shell in ash bash; do
  [ -e /bin/$shell ] && break
done
ln -sf /usr/lib/kaffe/bin/java $root/usr/bin
ln -sf $shell $root/bin/sh
lncp $root \
	/etc/host.conf \
	/etc/hosts \
	/etc/ld.so.cache \
	/etc/nsswitch.conf \
	/etc/protocols \
	/etc/resolv.conf \
	/bin/$shell \
	/bin/arch \
	/usr/lib/libkaffevm-1.0.6.so \
	/usr/lib/libkaffexprof-1.0.6.so \
	/usr/bin/kaffe
lncp $root `find /usr/lib/kaffe`
lncp $root `find /usr/share/kaffe`
cp --parents \
	/etc/localtime \
	/lib/libBrokenLocale.so.1 \
	/lib/libc.so.6 \
	/lib/libdl.so.2 \
	/lib/libm.so.6 \
	/lib/libnsl.so.1 \
	/lib/libnss_compat.so.2 \
	/lib/libnss_dns.so.2 \
	/lib/libnss_files.so.2 \
	/lib/libresolv.so.2 \
	/lib/ld-linux.so.2 \
	/usr/lib/libgmp.so.3 \
					$root
/etc/init.d/freenet-unstable start
