#!/bin/sh

# sets up an environment so that daemons don't actually get run,
# and proc is mounted for package installs which may require it.

# copyright 2004 vagrant@freegeek.org, distributed under the terms of the
# GNU General Public License version 2 or any later version.

if [ -r /etc/lessdisks-install.conf ]; then
  . /etc/lessdisks-install.conf
fi

if [ -r /etc/lessdisks/server.config ]; then
  . /etc/lessdisks/server.config
fi

if [ -n "$1" ]; then
  if [ -d $1 ]; then
    # use alternate chroot
    lessdisks_path="$1"
    shift
  fi
fi

if [ -z "$lessdisks_path" ] || [ ! -d "$lessdisks_path" ]; then
  exit 1
fi

mountpoint=$(which mountpoint)

do_chroot_mount() {
  chroot $lessdisks_path mount -t $@
  umounts="$umounts $3"
}

chroot_mount() {
  if [ -z "$mountpoint" ]; then
    do_chroot_mount $@
  else
    mountpoint -q $lessdisks_path/$3 || do_chroot_mount $@
  fi
}

# some package installs make use of /proc, so mount it
chroot_mount proc proc /proc
chroot_mount devpts devpts /dev/pts -o rw,gid=5,mode=620
chroot_mount tmpfs tmpfs /tmp

# set start-stop-daemon to behave like fake daemon
# so that packages which attempt to start servers don't do so while
# in the chroot.
LESSDISKS_START_STOP_DAEMON=fake chroot $lessdisks_path $@
# grab exit code from executed command
status="$?"

# unmount chrooted mountpoints 
for a in $umounts ; do
  umount $lessdisks_path/$a
done

# TODO support exit codes from the various umounts...
exit $status
