#!/bin/sh
#
# setup a debian installation for a Xen virtual domain
set -e

## additional packages
INCLUDE="ssh,less,postfix,postfix-pcre"
EXCLUDE="exim4,exim4-base,exim4-config,exim4-daemon-light,dhcp-client,fdutils,nano,ppp,pppconfig,pppoe,pppoeconf,tasksel,ipchains"

DIST=sarge
MIRROR=http://ftp.at.debian.org/debian/
VOLUMEGROUP=datavg
TARGET=/mnt
ROOTALIAS=user@example.com
SMTPRELAY=mail.example.com
TIMEZONE=Europe/Vienna
http_proxy=http://proxy:8080/
export http_proxy

cat <<HERE > /tmp/xentemplate
IPADDR=192.168.123.
NETMASK=255.255.255.0
GATEWAY=192.168.123.1

NAME=
ROOTSIZE=2G
MEMORY=128
HERE

vi /tmp/xentemplate

echo "Ready? Enter!"
read x

. /tmp/xentemplate

if [ -x /etc/xen/$NAME.xm ]; then
	echo "Config for $NAME already exists, fix it."
	exit 1
fi

lvcreate -L $ROOTSIZE -n $NAME-root $VOLUMEGROUP
mke2fs -b4096 -m1 -j /dev/$VOLUMEGROUP/$NAME-root
mount /dev/$VOLUMEGROUP/$NAME-root $TARGET


opt="--include=$INCLUDE --exclude=$EXCLUDE"

debootstrap $opt $DIST $TARGET $MIRROR

echo "proc	/proc	proc	defaults	0 0" >$TARGET/etc/fstab
echo "/dev/sda1	/	ext3	defaults	0 0" >>$TARGET/etc/fstab

target_kern=`uname -r | sed 's/0$/U/'`

cp -p /boot/System.map-$target_kern $TARGET/boot
cp -p /boot/config-$target_kern $TARGET/boot
cp -p /boot/vmlinuz-$target_kern $TARGET/boot

cat <<HERE >> $TARGET/etc/network/interfaces
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
	address $IPADDR
	netmask $NETMASK
	gateway $GATEWAY
HERE

cat <<HERE >> $TARGET/etc/hosts
127.0.0.1	localhost
$IPADDR	$NAME.example.com $NAME
HERE

rm $TARGET/etc/resolv.conf
cat /etc/resolv.conf > $TARGET/etc/resolv.conf
chmod 644 $TARGET/etc/resolv.conf

echo "$TIMEZONE" > $TARGET/etc/timezone
ln -fs /usr/share/zoneinfo/$TIMEZONE $TARGET/etc/localtime

echo $NAME > $TARGET/etc/hostname

cat <<HERE >> $TARGET/etc/apt/sources.list
deb $MIRROR $DIST main
deb http://security.debian.org $DIST/updates main
HERE

echo "Acquire::http::Proxy \"$http_proxy\";" >> $TARGET/etc/apt/apt.conf

chroot $TARGET /usr/bin/aptitude update
chroot $TARGET /usr/bin/aptitude upgrade
## need to install again, some links are borken otherwise.
chroot $TARGET /usr/bin/apt-get -y install --reinstall --no-remove -q postfix postfix-pcre < /dev/null

chroot $TARGET /etc/init.d/postfix stop
echo "root:	$ROOTALIAS" >> $TARGET/etc/aliases
chroot $TARGET /usr/bin/newaliases
chroot $TARGET /usr/sbin/postconf -e relayhost=$SMTPRELAY

mv $TARGET/lib/tls $TARGET/lib/tls.disabled
mkdir $TARGET/lib/tls
chmod 000 $TARGET/lib/tls

## disable virtual consoles
cp -p $TARGET/etc/inittab $TARGET/etc/inittab--
sed -e 's/^\([2-6]\)/#\1/' < $TARGET/etc/inittab-- > $TARGET/etc/inittab

## make xen config file

sed -e "s/NAME/$NAME/g; s/MEMORY/$MEMORY/g;" < /etc/xen/TEMPLATE > /etc/xen/$NAME.xm

umount $TARGET


echo "Ready to start?"
read x

xm create -f /etc/xen/$NAME.xm -c
