#!/bin/sh -e

divert() {
  prog="$1"
  mv $prog $prog.real
  cat > $prog <<EOF
#!/bin/sh

echo "Fake $prog called, doing nothing"
EOF
  chmod 755 $prog
}

undivert() {
  prog="$1"
  mv $prog.real $prog
}

DEBIAN_FRONTEND=noninteractive
export DEBIAN_FRONTEND

if test -n "$exclude"; then
    exclude=`echo $exclude | tr ' ' ,`
    opts="--exclude=$exclude"
fi

if test -n "$include"; then
    include=`echo $include | tr ' ' ,`
    opts="$opts --include=$include"
fi

if test -n "$basedebs"; then
    opts="$opts --unpack-tarball $basedebs"
fi

debootstrap $opts $dist $TARGET $mirror $script

echo "deb $mirror $dist main" > $TARGET/etc/apt/sources.list

rm -f $TARGET/var/lib/apt/lists/debootstrap.*

if test -z "$keepdebs"; then
    rm -f $TARGET/var/cache/apt/archives/*.deb
fi

echo $purge | tr ' ' '\n' | xargs --no-run-if-empty -t \
    chroot $TARGET dpkg --purge

echo $(hostname) > $TARGET/etc/hostname
if [ -f /etc/hosts ]; then
  install -m 644 /etc/hosts $TARGET/etc/hosts
fi

if test -n "$install"; then
    divert $TARGET/sbin/start-stop-daemon
    chroot $TARGET mount -t proc proc /proc
    chroot $TARGET apt-get update
    chroot $TARGET apt-get -y install $install
    echo "Killing any processes running on the target fs:"
    # kill any processes using the target fs
    fuser -k -v -m $TARGET || true
    chroot $TARGET umount /proc
    undivert $TARGET/sbin/start-stop-daemon
fi

if [ "$netconfig" != "no" ]; then
    . /tmp/rootstrap.netconf
    cat <<EOF >> $TARGET/etc/network/interfaces
auto lo
iface lo inet loopback

auto $interface
EOF
    if [ "$address" = "dhcp" ]; then
        cat <<EOF >> $TARGET/etc/network/interfaces
iface $interface inet dhcp
EOF
    else
        cat <<EOF >> $TARGET/etc/network/interfaces
iface $interface inet static
    address $address
    netmask $netmask
    gateway $gateway
EOF
    fi
    if [ ! -e $TARGET/etc/resolv.conf ]; then
        if [ -n "$domain" ]; then
            cat <<EOF >> $TARGET/etc/resolv.conf
search $domain
EOF
        fi
        if [ -n "$nameserver" ]; then
            cat <<EOF >> $TARGET/etc/resolv.conf
nameserver $nameserver
EOF
        fi
    fi
fi
