#!/bin/bash

NAME="$1"
CONTEXT="$2"
RELEASE="$3"
DEBOOTSTRAP_MIRROR="$4"
VHOSTNAME="$5"
VINTERFACE="$6"
PACKAGES="lsb-release,openssl,iproute,cron,sudo,openssh-server,locales"

if [ "$VHOSTNAME" != "none" ]; then
  VHOSTNAME_OPT="--hostname $VHOSTNAME"
fi

if [ ! -z "$VINTERFACE" ]; then
  VINTERFACE_OPT="--interface $VINTERFACE"
  VIP="`echo $VINTERFACE | cut -d : -f 2 | cut -d '/' -f 1`"
fi

# create basic vserver
vserver $NAME build -n $NAME --context $CONTEXT \
        $VHOSTNAME_OPT $VINTERFACE_OPT -m debootstrap -- \
        -d $RELEASE -m $DEBOOTSTRAP_MIRROR -- --include=$PACKAGES || exit 1

# copy in some some defaults
TARGET=/etc/vservers/$NAME/vdir/
cp /etc/apt/{preferences,sources.list} $TARGET/etc/apt/

# add minimum /etc/hosts entries
if [ "$VHOSTNAME" != "none" ]; then
  echo "$VIP $VHOSTNAME" > $TARGET/etc/hosts
fi

echo "127.0.0.1 $NAME" >> $TARGET/etc/hosts

# Setup is complete, now do the post-install stuff
vserver $NAME start                || exit 1
vserver $NAME exec apt-get update  || exit 1
vserver $NAME exec apt-get upgrade || exit 1

# custom puppet installation
#mkdir -p $TARGET/var/lib/puppet/modules/dbp
#cp /var/lib/puppet/modules/dbp/puppet_current.deb $TARGET/var/lib/puppet/modules/dbp/
#vserver $NAME exec dpkg --install var/lib/puppet/modules/dbp/puppet_current.deb
#vserver $NAME exec apt-get -fy install
#echo "Please sign now: puppetca --sign $NAME" >&2

echo "VServer $NAME created"