#!/bin/sh

set -e # DIE on errors

#########################
### MANAGE PARAMETERS ###
#########################

if [ $# -lt 5 ]; then 
	echo "Usage: $0 [ OPTIONS ] <PARAMETERS>"> /dev/stderr
	echo "Parameters are (in any order):"> /dev/stderr
	echo "                            -vpsid <id> : A number between 01 and 99"> /dev/stderr
	echo "                         -ram <size MB> : RAM size of the VPS in MB"> /dev/stderr
	echo "    -nic <ip>[,<netmask>[,<broadcast>]] : At least one -nic, can be multiple times"> /dev/stderr
	echo "                  -pass <root-password> : root pass for the VPS OS"> /dev/stderr
	echo "                 -os <operating-system> : System to setup"> /dev/stderr
	echo "              [ -gw <default-gateway> ] : Default gateway"> /dev/stderr
	echo "     [ -dns <default-dns-ip>[,<dns2>] ] : Default DNS server(s) in /etc/resolv.conf"> /dev/stderr
	echo "-------------------------------------------------------------------------" > /dev/stderr
	echo "All what is not enclosed with [] is mandatory!" > /dev/stderr
	echo "You have to provide at least ONE -nic options, as dtc-xen doesn't support bootstraping" > /dev/stderr
	echo "an operating system without a network setup" > /dev/stderr
	echo "If the netmask and broadcast are omited, the setup of the host OS will be used" > /dev/stderr
	echo "-------------------------------------------------------------------------" > /dev/stderr
	echo "" > /dev/stderr
	echo "<operating-system> can be one of the follwing:" > /dev/stderr
	echo "debian, debian-dtc, centos, neoshine, netbsd, xenhvm, manual" > /dev/stderr
	echo "or one of the operating system image names present in /usr/share/dtc-xen-os" > /dev/stderr
	echo "or one of the appliances folder names present in /usr/share/dtc-xen-app" > /dev/stderr
	echo "" > /dev/stderr
	echo "Options:" > /dev/stderr
	echo "                                 [ -v ] : Print the log in the standard output" > /dev/stderr
	echo "General options:" > /dev/stderr
	echo "                [ --disk-type lvm|vdb ] : Use LVM partition or disk image" > /dev/stderr
	echo "         [ --initrd <initrd-full-path ] : Path to the kernel initrd image to boot with" > /dev/stderr
	echo "         [ --kernel <kernel-full-path ] : Path to the kernel to boot with" > /dev/stderr
	echo "     [ --kernel-release <kernel-mods> ] : Path to the kernel modules folder" > /dev/stderr
	echo "          [ --kmod-path <kernel-mods> ] : Path to the kernel modules folder" > /dev/stderr
	echo "         [ --initrd <initrd-full-path ] : Path to the kernel initrd image to boot with" > /dev/stderr
	echo "                         [ --vps-fqdn ] : Customizes the hostname of the VPS" > /dev/stderr
	echo "                              [ --mac ] : MAC address of the VPS"
	echo "                           [ --bridge ] : Network Bridge" > /dev/stderr
	echo "                           [ --maxmem ] : Maximum domain memory in MB" > /dev/stderr
	echo "                            [ --vcpus ] : Number of vcpus" > /dev/stderr
	echo "                             [ --cpus ] : CPU settings" > /dev/stderr
	echo "                           [ --cpucap ] : Set the maximum amount of cpu" > /dev/stderr
	echo "                        [ --cpuweight ] : Set the cpu time ratio to be allocated to the domain" > /dev/stderr
	echo "                          [ --pae 0|1 ] : Disable or enable PAE of HVM domain " > /dev/stderr
	echo "                         [ --acpi 0|1 ] : Disable or enable ACPI of HVM domain" > /dev/stderr
	echo "                         [ --apic 0|1 ] : Disable or enable APIC mode " > /dev/stderr
	echo "                           [ --keymap ] : Set keyboard layout used " > /dev/stderr
	echo "                           [ --locale ] : Set locale" > /dev/stderr
	echo "               [ --virt-type <xen|vz> ] : Virtualization (for the moment, xen or vz only)" > /dev/stderr
	echo "Options specific to Xen HVM guests:" > /dev/stderr
	echo "               [ --vnc-pass <VNCPASS> ] : VNC password for the physical console" > /dev/stderr
	echo "              [ --boot-iso <file.iso> ] : CDROM device to boot on" > /dev/stderr
	echo "" > /dev/stderr
	echo "-------------------------------------------------------------------------" > /dev/stderr
	echo "Example1: $0 -v -vpsid 01 -ram 512 -nic 192.168.2.176,255.255.255.0,192.168.2.255 -pass MyRootPass -os debian -gw 192.168.2.1 -dns 192.168.2.1" > /dev/stderr
	echo "" > /dev/stderr
	echo "Example2: $0 -vpsid 02 -ram 512 -nic 192.168.9.2 -nic 192.168.9.3 -gw 192.168.9.1 \\" > /dev/stderr
	echo "   -dns 192.168.9.1 -pass MyRootPass -os kde-nx-server-3.3.0" > /dev/stderr
	exit 1
fi

# Source the configuration in the config file!
if [ -f /etc/dtc-xen/dtc-xen.conf ] ; then
	. /etc/dtc-xen/dtc-xen.conf
fi

if [ -n "$debian_release" ] ; then DEBIAN_RELEASE="$debian_release" ; fi
if [ -n "$debian_repo" ] ; then DEBIAN_REPOS="$debian_repo" ; fi

# Some defaults if not present in the conf file...
if [ -z "$DEBIAN_RELEASE" ] ; then DEBIAN_RELEASE=lenny ; fi
if [ -z "$DEBIAN_REPOS" ] ; then DEBIAN_REPOS="http://ftp.us.debian.org/debian/" ; fi

# Manage options in any order...
DO_EXIT="no"
NUM_NIC=0
REDIRECTOUTPUT=true
VNC_PASSWORD=`dd if=/dev/random bs=64 count=1 2>|/dev/null | md5sum | cut -d' ' -f1`
for i in $@ ; do
#	echo "Found option: ${1} ${2}"
	case "${1}" in
	"--short-circuit")
		# This one is for debug purposes, do not use...
		SHORT_CIRCUIT="yes"
		shift
		;;
	"-vpsid")
		if [ -z "${2}" ] ; then echo "Parameter for option -vpsid is missing" > /dev/stderr ; DO_EXIT="yes" ; fi
		VPSNUM="${2}"
		shift
		shift
		;;
	"-ram")
		if [ -z "${2}" ] ; then echo "Parameter for option -ram is missing" > /dev/stderr ; DO_EXIT="yes" ; fi
		VPSMEM="${2}"
		shift
		shift
		;;
	"--mac")
		MAC_ADDR="${2}"
		shift
		shift
		;;
	"--bridge")
		XEN_BR="${2}"
		shift
		shift
		;;
	"--maxmem")
		MAXMEM="${2}"
		shift
		shift
		;;
	"--vcpus")
		VCPUS="${2}"
		shift
		shift
		;;
	"--cpus")
		CPUS="${2}"
		shift
		shift
		;;
	"--cpucap")
		CPUCAP="${2}"
		shift
		shift
		;;
	"--cpuweight")
		CPUWEIGHT="${2}"
		shift
		shift
		;;
	"--pae")
		PAE="${2}"
		shift
		shift
		;;
	"--acpi")
		ACPI="${2}"
		shift
		shift
		;;
	"--apic")
		APIC="${2}"
		shift
		shift
		;;
	"--keymap")
		KEYMAP="${2}"
		shift
		shift
		;;
	"--locale")
		LOCALE="${2}"
		shift
		shift
		;;
	"-nic")
		if [ -z "${2}" ] ; then echo "Parameter for option -nic is missing" > /dev/stderr ; exit 1 ; fi
		# Manage the nics to give it as parameters to the setup-vps-network script
		PARAM=${2}
		PARAM_TMP=${2}
		if [ -z ""`echo ${PARAM} | cut -s -d"," -f2` ] ; then
			if [ -z "${NETMASK}" ] ; then
				echo "Parameter NETMASK not found: either edit /etc/dtc-xen/dtc-xen.conf or use a netmask parameter" > /dev/stderr ; exit 1
			fi
			PARAM="${PARAM},${NETMASK}"
		fi
		if [ -z ""`echo ${PARAM_TMP} | cut -s -d"," -f3` ] ; then
			if [ -z "${BROADCAST}" ] ; then
				echo "Parameter BROADCAST not found: either edit /etc/dtc-xen/dtc-xen.conf or use a broadcast parameter" > /dev/stderr ; exit 1
			fi
			PARAM="${PARAM},${BROADCAST}"
		fi
		if [ "${NUM_NIC}" = 0 ] ; then
			ALL_IPADDRS=`echo ${PARAM} | cut -d"," -f1`
			FW_NICS_CMD="-nic ${PARAM}"
			NICS=${PARAM}
		else
			ALL_IPADDRS="${ALL_IPADDRS} "`echo ${PARAM} | cut -d"," -f1`
			FW_NICS_CMD="${FW_NICS_CMD} -nic ${PARAM}"
			NICS=$NICS"
"${PARAM}
		fi
		NUM_NIC=$(( ${NUM_NIC} + 1 ))
		shift
		shift
		;;
	"-pass")
		if [ -z "${2}" ] ; then echo "Parameter for option -pass is missing" > /dev/stderr ; DO_EXIT="yes" ; fi
		PASSWORD=${2}
		shift
		shift
		;;
	"-os")
		if [ -z "${2}" ] ; then echo "Parameter for option -os is missing" > /dev/stderr ; DO_EXIT="yes" ; fi
		DISTRO=${2}
		shift
		shift
		;;
	"-gw")
		if [ -z "${2}" ] ; then echo "Parameter for option -gw is missing" > /dev/stderr ; DO_EXIT="yes" ; fi
		GATEWAY="$2"
		shift
		shift
		;;
	"-v")
		REDIRECTOUTPUT=false
		shift
		;;
	"--vnc-pass")
		if [ -z "${2}" ] ; then echo "Parameter for option --vnc-pass is missing" > /dev/stderr ; DO_EXIT="yes" ; fi
		VNC_PASSWORD="$2"
		shift
		shift
		;;
	"--boot-iso")
		if [ -z "${2}" ] ; then echo "Parameter for option --boot-iso is missing" > /dev/stderr ; DO_EXIT="yes" ; fi
		BOOT_ISO="$2"
		shift
		shift
		;;
	"-dns")
		DNS=${2}
		shift
		shift
		;;
	"--vps-fqdn")
		if [ -z "${2}" ] ; then echo "Parameter for option --vps-fqdn is missing" > /dev/stderr ; DO_EXIT="yes" ; fi
		VPS_FQDN=${2}
		shift
		shift
		;;
	"--vps-domain")
		if [ -z "${2}" ] ; then echo "Parameter for option --vps-domain is missing" > /dev/stderr ; DO_EXIT="yes" ; fi
		VPS_DOMAIN=${2}
		shift
		shift
		;;
	"--virt-type")
		if [ -z "${2}" ] ; then echo "Parameter for option --virt-type is missing" > /dev/stderr ; DO_EXIT="yes" ; fi
		VIRT_TYPE=${2}
		shift
		shift
		;;
	"--kernel")
		if [ -z "${2}" ] ; then echo "Parameter for option --kernel is missing" > /dev/stderr ; DO_EXIT="yes" ; fi
		KERNELPATH="$2"
		shift
		shift
		;;
	"--kernel-release")
		if [ -z "${2}" ] ; then echo "Parameter for option --kernel-release is missing" > /dev/stderr ; DO_EXIT="yes" ; fi
		KERNEL_RELEASE=${2}
		shift
		shift
		;;
	"--kmod-path")
		if [ -z "${2}" ] ; then echo "Parameter for option --kmod-path is missing" > /dev/stderr ; DO_EXIT="yes" ; fi
		KMOD_PATH=${2}
		shift
		shift
		;;
	"--initrd")
		if [ -z "${2}" ] ; then echo "Parameter for option --initrd is missing" > /dev/stderr ; DO_EXIT="yes" ; fi
		INITRDPATH=${2}
		shift
		shift
		;;
	"--disk-type")
		if [ -z "${2}" ] ; then echo "Parameter for option --disk-type is missing" > /dev/stderr ; DO_EXIT="yes" ; fi
		IMAGE_TYPE=${2}
		shift
		shift
		;;
	*)
		;;
	esac
done

# Detect the virtualization type if not are given on the command line
if [ -z "${VIRT_TYPE}" ] ; then
	if [ -d /proc/xen ] ; then
		VIRT_TYPE="xen"
	fi
	if [ -d /proc/vz ] ; then
		VIRT_TYPE="vz"
	fi
fi
if [ -z "${VIRT_TYPE}" ] ; then
	echo "Could not find /proc/xen or /proc/vz: impossible to tell if Xen or VZ is running. Will exit now" > /dev/stderr
	DO_EXIT="yes"
fi

# Default to using xvdX and not sdaX
if [ -z "${XEN_DOMU_HDD_DEV_TYPE}" ] ; then
	XEN_DOMU_HDD_DEV_TYPE=xvd
fi

if [ -z "${VPSNUM}" ] ; then
	echo "No VPS number. Please use -vpsid <id>." > /dev/stderr
	DO_EXIT="yes"
fi

if [ -z "${VPSMEM}" ] ; then
	echo "No RAM size. Please use -ram <size MB>" > /dev/stderr
	DO_EXIT="yes"
fi

if [ -z "${GATEWAY}" ] ; then
	echo "No gateway ip. Please use -gw <gateway-IP> or edit /etc/dtc-xen/dtc-xen.conf" > /dev/stderr
	DO_EXIT="yes"
fi

if [ -z "${PASSWORD}" ] ; then
	echo "No root pass. Please use -pass <root-password>" > /dev/stderr
	DO_EXIT="yes"
fi

if [ -z "${DISTRO}" ] ; then
	echo "No distribution selected, please use -os <linux-distribution>" > /dev/stderr
	DO_EXIT="yes"
fi

if [ -z "${KERNELPATH}" ] ; then
	TESTME=/boot/vmlinuz-`uname -r`
	if [ -e ${TESTME} ] ; then
		KERNELPATH=${TESTME}
	else
		echo "No kernel was found. Either use --kernel, or define a KERNELPATH in /etc/dtc-xen/dtc-xen.conf, or make sure you have installed Xen" > /dev/stderr
	fi
fi

if [ -z "${KERNEL_RELEASE}" ] ; then
	KERNEL_RELEASE=`uname -r`
fi

if [ -z "${KMOD_PATH}" ] ; then
	TESTME=/lib/modules/`uname -r`
	if [ -e ${TESTME} ] ; then
		KMOD_PATH=/lib/modules/`uname -r`
	else
		echo "No kernel was found. Either use --kmod-path, or define a KMOD_PATH in /etc/dtc-xen/dtc-xen.conf, or make sure you have installed Xen" > /dev/stderr
	fi
fi

if [ -z "${INITRDPATH}" ] ; then
	TESTME=/boot/initrd.img-`uname -r`
	if [ -e "${TESTME}" ] ; then
		INITRDPATH=${TESTME}
	else
		TESTME=/boot/initrd-`uname -r`.img
		if [ -e "${TESTME}" ] ; then
			INITRDPATH=${TESTME}
		else
			echo "WARNING! No initrd image found! Will continue without an initial ramdisk image." > /dev/stderr
		fi
	fi
fi

if [ -z "${DNS}" ] ; then
	DNS=`grep "nameserver" /etc/resolv.conf | head -n 1 | cut -d" " -f2`
	echo "WARNING! No dns defined, guessed: ${DNS}"
fi

if [ ${DO_EXIT} = "yes" ] ; then
	echo "Parameters not validated: will exit now!" > /dev/stderr
	exit 1
fi

# Figure out the VPS mount point
if [ -n "${provisioning_mount_point}" ] ; then
	VPSGLOBPATH="${provisioning_mount_point}"
else
	VPSGLOBPATH="$VPS_MOUNTPOINT"
fi

if [ -z "${IMAGE_TYPE}" ] ; then
	IMAGE_TYPE=lvm
fi

# Figure out the LVM name from dtc-xen.conf
if [ "${IMAGE_TYPE}" = "lvm" ] ; then
	LVMNAME=`dtc-xen-volgroup`
	if [ -z "$LVMNAME" ] ; then
		echo "Could not determine volume group from which to provision the volume" 1>&2
		echo "You might want to set provisioning_volgroup in dtc-xen.conf" 1>&2
		exit 78
	fi
fi
FSTAB_LVMNAME=`echo ${LVMNAME} | sed -e 's/-/--/g'`

# Finds the kernel name
if [ -z "${KERNELPATH}" ] ; then
	if [ -e /boot/vmlinuz-`uname -r` ] ; then
		KERNELPATH=/boot/vmlinuz-`uname -r`
	fi
fi
if [ -z "${KERNELPATH}" ] ; then
	echo "Could not find the kernel image file!" 1>&2
	exit 78
fi

VPSNAME=xen${VPSNUM}
NODE_FQDN=`hostname --fqdn`
# Manuel, what we have been discussing about using mx.xenXX.dom0-fqdn or xenXX.dom0-fqdn by default
# is right here! I believe we should give an entire domain to each VPS, so I want "mx.", but maybe
# can make this configurable, there's an option now as you see, this is just the default...
if [ -z "${VPS_DOMAIN}" ] ; then
	VPS_DOMAIN="${VPSNAME}.${NODE_FQDN}"
fi
if [ -z "${VPS_FQDN}" ] ; then
	VPS_FQDN="mx.${VPS_DOMAIN}"
fi

if [ -z "${MAC_ADDR}" ] ; then
	if [ ! -z "${vps_mac_prefix}" ] ; then
		MAC_ADDR=${vps_mac_prefix}:${VPSNUM}
	fi
fi

if [ -z "${XEN_BR}" ] ; then
	if [ ! -z "${bridge}" ] ; then
		XEN_BR=${bridge}
	fi
fi

FOUNDED_ARCH=`uname -m`

case "$FOUNDED_ARCH" in
	i386)
		DEBIAN_BINARCH=i386
		CENTOS_BINARCH=i386
		;;
	i436)
		DEBIAN_BINARCH=i386
		CENTOS_BINARCH=i386
		;;
	i586)
		DEBIAN_BINARCH=i386
		CENTOS_BINARCH=i386
		;;
	i686)
		DEBIAN_BINARCH=i386
		CENTOS_BINARCH=i386
		;;
	x86_64)
		DEBIAN_BINARCH=amd64
		CENTOS_BINARCH=x86_64
		;;
	*)
		echo "Unrecognized arch: exiting!"
		exit 1
		;;
esac

# default distro to debian
if [ -z "$DISTRO" ]; then
	DISTRO=debian
fi

LVCREATE=/sbin/lvcreate
MKFS=/sbin/mkfs.ext3
MKDIR=/bin/mkdir
MKSWAP=/sbin/mkswap
MOUNT=/bin/mount
UMOUNT=/bin/umount
DEBOOTSTRAP=/usr/sbin/debootstrap

# We forward always this list of parameters to all scripts:
calc_formard_parms (){
	HVM_PARMS=""
	if [ -z "${VNC_PASSWORD}" ] ; then
		HVM_PARMS="--vnc-pass ${VNC_PASSWORD}"
	fi
	if [ -z "${BOOT_ISO}" ] ; then
		HVM_PARMS="${HVM_PARMS} --boot-iso ${BOOT_ISO}"
	fi

	KERNEL_P="--kernel ${KERNELPATH} --kernel-release ${KERNEL_RELEASE} --kmod-path ${KMOD_PATH} --initrd ${INITRDPATH}"
	FW_PARAMS="--disk-type ${IMAGE_TYPE} --xen-domu-hdd-dev-type ${XEN_DOMU_HDD_DEV_TYPE} -os ${DISTRO} -ram ${VPSMEM} -path ${VPSGLOBPATH}/${VPSNUM} -vpsid ${VPSNUM} --vps-fqdn ${VPS_FQDN} --vps-domain ${VPS_DOMAIN} --node-fqdn ${NODE_FQDN} ${FW_NICS_CMD} -dns ${DNS} -gw ${GATEWAY} --virt-type ${VIRT_TYPE} ${KERNEL_P}"
	if [ -n "${MAC_ADDR}" ] ; then
		FW_PARAMS="${FW_PARAMS} --mac ${MAC_ADDR}"
	fi
	if [ -n "${XEN_BR}" ] ; then
		FW_PARAMS="${FW_PARAMS} --bridge ${XEN_BR}"
	fi
	if [ -n "${MAXMEM}" ] ; then
		FW_PARAMS="${FW_PARAMS} --maxmem ${MAXMEM}"
	fi
	if [ -n "${VCPUS}" ] ; then
		FW_PARAMS="${FW_PARAMS} --vcpus ${VCPUS}"
	fi
	if [ -n "${CPUS}" ] ; then
		FW_PARAMS="${FW_PARAMS} --cpus ${CPUS}"
	fi
	if [ -n "${CPUCAP}" ] ; then
		FW_PARAMS="${FW_PARAMS} --cpucap ${CPUCAP}"
	fi
	if [ -n "${CPUWEIGHT}" ] ; then
		FW_PARAMS="${FW_PARAMS} --cpuweight ${CPUWEIGHT}"
	fi
	if [ -n "${PAE}" ] ; then
		FW_PARAMS="${FW_PARAMS} --pae ${PAE}"
	fi
	if [ -n "${ACPI}" ] ; then
		FW_PARAMS="${FW_PARAMS} --acpi ${ACPI}"
	fi
	if [ -n "${APIC}" ] ; then
		FW_PARAMS="${FW_PARAMS} --apic ${APIC}"
	fi
	if [ -n "${KEYMAP}" ] ; then
		FW_PARAMS="${FW_PARAMS} --keymap ${KEYMAP}"
	fi
	if [ -n "${LOCALE}" ] ; then
		FW_PARAMS="${FW_PARAMS} --locale ${LOCALE}"
	fi
	if [ -z "${HVM_PARMS}" ] ; then
		FW_PARAMS="${FW_PARAMS} ${HVM_PARMS}"
	fi
	if [ -z "${LVMNAME}" ] ; then
		FW_PARAMS="${FW_PARAMS} --lvm-name ${LVMNAME}"
	fi
	if [ -n "${XENU_EXTRA_PARM}" ] ; then
		FW_PARAMS="${FW_PARAMS} --xenu_extra_parm ${XENU_EXTRA_PARM}"
	fi
}
calc_formard_parms

#####################################################
### Check / creation of the DTC-Xen user / group ####
#####################################################
GETENT=getent
XENUSERS=xenusers
XEN_USER_HOME=/var/lib/dtc-xen/ttyssh_home
if ${GETENT} passwd xen${VPSNUM} >/dev/null ; then
	echo "User xen${VPSNUM} already exists: skipping creation!"
else
	if [ -x /usr/sbin/useradd ] ; then
		if [ ! -x /bin/bash ] ; then
			echo "Could not find the bash shell!"
			exit 1
		fi
		/usr/sbin/useradd --home "${XEN_USER_HOME}/xen${VPSNUM}" -m -s /usr/bin/dtc-xen_userconsole -g ${XENUSERS} xen${VPSNUM}
	else
		echo "Cound not find the useradd binary!"
		exit 1
	fi
fi
# Modify an eventual wrong old config
mkdir -p "${XEN_USER_HOME}/xen${VPSNUM}/.ssh"
chown -R xen${VPSNUM}:${XENUSERS} "${XEN_USER_HOME}/xen${VPSNUM}"
usermod -d "${XEN_USER_HOME}/xen${VPSNUM}" -g ${XENUSERS} -s /usr/bin/dtc-xen_userconsole xen${VPSNUM}

######################################
### REDIRECTION OF STANDARD OUTPUT ###
######################################

# redirect stdout and stderr to log files, so we can see what happened during install
if [ "$REDIRECTOUTPUT" = "true" ] ; then
	echo "Redirecting standard output to $VPSGLOBPATH/$VPSNUM.stdout..."
	echo "Redirecting standard error to $VPSGLOBPATH/$VPSNUM.stderr..."
	if [ -e $VPSGLOBPATH/$VPSNUM.stdout ]; then
		mv $VPSGLOBPATH/$VPSNUM.stdout $VPSGLOBPATH/$VPSNUM.stdout.old
	fi
	if [ -e $VPSGLOBPATH/$VPSNUM.stderr ]; then
		mv $VPSGLOBPATH/$VPSNUM.stderr $VPSGLOBPATH/$VPSNUM.stderr.old
	fi
	
	exec 1>$VPSGLOBPATH/$VPSNUM.stdout
	exec 2>$VPSGLOBPATH/$VPSNUM.stderr
fi


############################
### FORMAT THE PARTITION ###
############################
if ! [ "${VIRT_TYPE}" = "vz" -a -n "${VZ_NO_MOUNT}" ] ; then
	if [ "${DISTRO}" = "xenhvm" ] ; then
		echo "Not formating disks, xen HVM will use emulated hard drives."
	elif [ "$DISTRO" = "netbsd" ] ; then
		echo "Not formating disks, NetBSD will use emulated hard drives."
	else
		echo "Creating disks..."

		set +e
		$UMOUNT ${VPSGLOBPATH}/${VPSNUM} 2> /dev/null
		rmdir ${VPSGLOBPATH}/${VPSNUM} 2> /dev/null
		set -e

		$MKDIR -p ${VPSGLOBPATH}/${VPSNUM}
		if [ "$IMAGE_TYPE" = "lvm" ]; then
			if [ -z "${SHORT_CIRCUIT}" ] ; then
				$MKFS -q /dev/${LVMNAME}/${VPSNAME}
				$MKSWAP /dev/${LVMNAME}/${VPSNAME}swap
			else
				echo "Not doing MKFS: debuging..."
			fi
	
			if grep ${VPSNAME} /etc/fstab >/dev/null ; then
				echo "LV already exists in fstab: skipping"
			else
				echo "/dev/mapper/${FSTAB_LVMNAME}-${VPSNAME}  ${VPSGLOBPATH}/${VPSNUM} ext3    defaults,noauto 0 0" >>/etc/fstab
			fi

		else
			# support for file backed VPS
			# Create files for hdd and swap (only if they don't exist)
			if [ ! -e $VPSGLOBPATH/${VPSNAME}.img ]; then
				dd if=/dev/zero of=$VPSGLOBPATH/${VPSNAME}.img bs=1G seek=${VPSHDD} count=1
			fi
			$MKFS -F $VPSGLOBPATH/${VPSNAME}.img
			if [ ! -e $VPSGLOBPATH/${VPSNAME}.swap.img ]; then
				dd if=/dev/zero of=$VPSGLOBPATH/${VPSNAME}.swap.img bs=1M seek=${VPSMEM} count=1
			fi
			$MKSWAP $VPSGLOBPATH/${VPSNAME}.swap.img
			if grep ${VPSNAME} /etc/fstab >/dev/null ; then
				echo "LoopMount already exists in fstab: skipping"
			else
				echo "$VPSGLOBPATH/${VPSNAME}.img  ${VPSGLOBPATH}/${VPSNUM}  ext3	defaults,noauto,loop 0 0" >>/etc/fstab
			fi
		fi
		if ! [ "${VIRT_TYPE}" = "vz" -a -n "${VZ_NO_MOUNT}" ] ; then
			echo "Mounting..."
			$MOUNT ${VPSGLOBPATH}/${VPSNUM}
		fi
	fi
fi

####################
### BOOTSTRAPING ###
####################

echo "Bootstraping..."

# Search if we are installing an appliance that depends on a particular distribution
APPLIANCE=""
if [ -e /usr/share/dtc-xen-app/${DISTRO}/depends ] ; then
	APPLIANCE="${DISTRO}"
	DISTRO=`cat /usr/share/dtc-xen-app/${DISTRO}/depends`
fi

# Rebuild the params since DISTRO might have change if we use appliances.
calc_formard_parms

if [ "$DISTRO" = "xenhvm" -o "$DISTRO" = "netbsd" ] ; then
	echo "There's nothing to bootstrap, as you will use the provided distribution installer in this case."
elif [ "$DISTRO" = "centos" -o "$DISTRO" = "neoshine" ] ; then
	if [ -z "${SHORT_CIRCUIT}" ] ; then
		if [ "$DISTRO" = "centos" ] ; then
			/usr/sbin/dtc_install_centos /var/lib/dtc-xen/yum "$VPSGLOBPATH/$VPSNUM"
		else
			/usr/sbin/dtc_install_neoshine /var/lib/dtc-xen/yum "$VPSGLOBPATH/$VPSNUM"
		fi
		# Copy the CentOS inittab if dom0 is CentOS as well, otherwise no console...
		if [ -f /etc/redhat-release ] ; then
			cp /etc/dtc-xen/inittab $VPSGLOBPATH/$VPSNUM/etc
		fi
	else
		echo "Not bootstraping: debuging..."
	fi
elif [ "$DISTRO" = "debian" -o "$DISTRO" = "debian-dtc" ] ; then
	if [ ${DEBIAN_BINARCH} = "i386" ] ; then
		ADD_LIBC="libc6-xen,"
	else
		ADD_LIBC=""
	fi
	if [ -z "${SHORT_CIRCUIT}" ] ; then
		if [ -z "${debian_added_debs}" ] ; then
			debian_added_debs=module-init-tools,locales,udev,joe,screen
		fi
		echo $DEBOOTSTRAP --verbose --include=${ADD_LIBC}${debian_added_debs} --arch ${DEBIAN_BINARCH} ${DEBIAN_RELEASE} ${VPSGLOBPATH}/${VPSNUM} ${DEBIAN_REPOS}
		$DEBOOTSTRAP --verbose --include=${ADD_LIBC}${debian_added_debs} --arch ${DEBIAN_BINARCH} ${DEBIAN_RELEASE} ${VPSGLOBPATH}/${VPSNUM} ${DEBIAN_REPOS} || debret=$?
	else
		echo "Not bootstraping: debuging..."
	fi
	if [ "$debret" != "" ]; then
		echo "Failed to install $DISTRO via bootstrap!!"
		exit $debret
	fi
else
	if [ -e /usr/share/dtc-xen-os/${DISTRO}/install_os ] ; then
		/usr/share/dtc-xen-os/${DISTRO}/install_os ${FW_PARAMS}
	else
		echo "Currently, you will have to manually install your distro... sorry :)"
		echo "The filesystem is mounted on ${VPSGLOBPATH}/${VPSNUM}"
		echo "Remember to unmount (umount ${VPSGLOBPATH}/${VPSNUM}) before booting the OS"
		echo "if you are not running VZ."
		echo "Cheers!"
		exit
	fi
fi

########################
### OS CUSTOMIZATION ###
########################

echo "Customizing vps fstab, hosts and hostname for distro ${DISTRO}..."
if [ "$DISTRO" = "debian" -o "$DISTRO" = "debian-dtc" -o "$DISTRO" = "centos" -o "$DISTRO" = "neoshine" ] ; then
	/usr/sbin/dtc-xen_domUconf_standard ${FW_PARAMS}
	if [ "$DISTRO" = "debian" -o "$DISTRO" = "debian-dtc" ] ; then
		sed "s/VPS_HOSTNAME/${VPS_FQDN}/" /etc/dtc-xen/motd >${VPSGLOBPATH}/${VPSNUM}/etc/motd.tail
	fi
else
	if [ -x /usr/share/dtc-xen-os/${DISTRO}/custom_os ] ; then
		/usr/share/dtc-xen-os/${DISTRO}/custom_os ${FW_PARAMS}
	fi
fi

if [ "$DISTRO" = "netbsd" -o "$DISTRO" = "xenhvm" ] ; then
	echo "Not changing password for netbsd or xenhvm!"
else
	echo -n "Setting root password..."
	chroot ${VPSGLOBPATH}/${VPSNUM} sh -c "echo root:$PASSWORD | chpasswd"
	if [ $? -eq 0 ] ; then
		echo "[OK]"
	else
		echo "[FAIL]"
	fi
fi

####################################
### NETWORK CONFIG CUSTOMIZATION ###
####################################

# handle the network setup
echo "Setting-up network for distro ${DISTRO}..."
if [ "$DISTRO" = "netbsd" -o "$DISTRO" = "xenhvm" ] ; then
	echo "Nothing to do: it's BSD or xenhvm!"
elif [ "$DISTRO" = "centos" -o "$DISTRO" = "neoshine" ] ; then
	/usr/sbin/dtc-xen_domUconf_network_redhat ${FW_PARAMS}
elif [ "$DISTRO" = "debian" -o "$DISTRO" = "debian-dtc" ] ; then
	/usr/sbin/dtc-xen_domUconf_network_debian ${FW_PARAMS}

	if [ -f /etc/dtc-xen/sources.list ] ; then
		cp /etc/dtc-xen/sources.list ${VPSGLOBPATH}/${VPSNUM}/etc/apt
	else
		cp /etc/apt/sources.list ${VPSGLOBPATH}/${VPSNUM}/etc/apt
	fi
else
	if [ -x /usr/share/dtc-xen-os/${DISTRO}/setup_network ] ; then
		/usr/share/dtc-xen-os/${DISTRO}/setup_network ${FW_PARAMS}
	else
		echo "Not implemented for other distros yet"
		exit 1
	fi
fi

#################################
### XEN STARTUP FILE CREATION ###
#################################
if [ "${VIRT_TYPE}" = "xen" ] ; then
	/usr/sbin/dtc-xen_domU_gen_xen_conf ${FW_PARAMS}
fi
if [ "${VIRT_TYPE}" = "vz" ] ; then
	/usr/sbin/dtc-xen_domU_gen_vz_conf ${FW_PARAMS}
fi

########################
### SOME LAST THINGS ###
########################

# need to install 2.6 compat stuff for centos3
if [ "$DISTRO" = "centos" -a "$CENTOS_RELEASE" = "neoshine" ]; then
	mkdir -p ${VPSGLOBPATH}/${VPSNUM}/tmp
	wget -O ${VPSGLOBPATH}/${VPSNUM}/tmp/yum.conf.mini ftp://ftp.pasteur.fr/pub/BIS/tru/2.6_CentOS-3/yum.conf.mini
	chroot ${VPSGLOBPATH}/${VPSNUM} yum -c /tmp/yum.conf.mini -y update	
	chroot ${VPSGLOBPATH}/${VPSNUM} yum -c /tmp/yum.conf.mini install initscripts_26
	chroot ${VPSGLOBPATH}/${VPSNUM} rm /tmp/yum.conf.mini
fi

# Remove the persistent-net udev config, so the eth wont get renamed
# when changing MAC, which is extremely not cool when migrating a VM
if [ "$DISTRO" = "debian-dtc" -o "$DISTRO" = "debian" ] ; then
	rm -f ${VPSGLOBPATH}/${VPSNUM}/etc/udev/rules.d/z25_persistent-net.rules
	rm -f ${VPSGLOBPATH}/${VPSNUM}/etc/udev/rules.d/70-persistent-net.rules
fi

if [ "$DISTRO" = "debian-dtc" ] ; then
	cp /usr/share/dtc-xen/dtc-panel_autodeploy.sh ${VPSGLOBPATH}/${VPSNUM}/root/dtc-panel_autodeploy
	chmod +x ${VPSGLOBPATH}/${VPSNUM}/root/dtc-panel_autodeploy
	cp /usr/share/dtc-xen/selection_config_file ${VPSGLOBPATH}/${VPSNUM}/root
	# We don't want the devices to be created, as this would fail in VZ (to be checked...)
	if [ "${VIRT_TYPE}" = "vz" ] ; then
		echo "dtc-postfix-courier dtc/conf_omit_dev_mknod boolean true
dtc-postfix-courier dtc/conf_omit_dev_mknod seen true" >>${VPSGLOBPATH}/${VPSNUM}/root/selection_config_file
	fi
	echo "#!/bin/sh

### BEGIN INIT INFO
# Provides:          dtc-panel_autodeploy
# Required-Start:    $remote_fs
# Required-Stop:     $remote_fs
# Should-Start:      $network $syslog
# Should-Stop:       $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Automatically installs DTC
# Description:       Automatically installs DTC
#                    uppon boot time
### END INIT INFO

case \"\$1\" in
start)
	cd /root
	/root/dtc-panel_autodeploy ${PASSWORD}

	update-rc.d -f dtc-panel_autodeploy remove
;;
*)
	echo -n ""
;;
esac
exit 0
" >${VPSGLOBPATH}/${VPSNUM}/etc/init.d/dtc-panel_autodeploy
	chmod +x ${VPSGLOBPATH}/${VPSNUM}/etc/init.d/dtc-panel_autodeploy

	chroot ${VPSGLOBPATH}/${VPSNUM} update-rc.d dtc-panel_autodeploy defaults
fi

##########################################
### SETUP APPLIANCE SCRIPT AND FOLDERS ###
##########################################
if [ ! -z "${APPLIANCE}" ] ; then
	echo "Setting up appliance boot-stage setup script ${APPLIANCE}..."
	cp /usr/share/dtc-xen-app/${APPLIANCE}/setup-script ${VPSGLOBPATH}/${VPSNUM}/root/dtc-xen-appliance-setup
	if [ -e /usr/share/dtc-xen-app/${APPLIANCE}/setup-folder ] ; then
		cp -rf /usr/share/dtc-xen-app/${APPLIANCE}/setup-folder ${VPSGLOBPATH}/${VPSNUM}/root/
	fi
	echo "#!/bin/sh

cd /root
/root/dtc-xen-appliance-setup ${PASSWORD}

rm /etc/rc2.d/S99dtc-xen-appliance
rm /etc/rc3.d/S99dtc-xen-appliance
rm /etc/rc4.d/S99dtc-xen-appliance
rm /etc/rc5.d/S99dtc-xen-appliance
rm /etc/init.d/dtc-xen-appliance
" >${VPSGLOBPATH}/${VPSNUM}/etc/init.d/dtc-xen-appliance
	chmod +x ${VPSGLOBPATH}/${VPSNUM}/etc/init.d/dtc-xen-appliance
	ln -s ../init.d/dtc-xen-appliance ${VPSGLOBPATH}/${VPSNUM}/etc/rc2.d/S99dtc-xen-appliance
	ln -s ../init.d/dtc-xen-appliance ${VPSGLOBPATH}/${VPSNUM}/etc/rc3.d/S99dtc-xen-appliance
	ln -s ../init.d/dtc-xen-appliance ${VPSGLOBPATH}/${VPSNUM}/etc/rc4.d/S99dtc-xen-appliance
	ln -s ../init.d/dtc-xen-appliance ${VPSGLOBPATH}/${VPSNUM}/etc/rc5.d/S99dtc-xen-appliance
fi

###############################################################
### Custom postinstall script (user defined, not mandatory) ###
###############################################################
if [ -n "${custom_postinstall_script}" ] ; then
	if [ -x ${custom_postinstall_script} ] ; then
		${custom_postinstall_script} ${FW_PARAMS}
	fi
fi

####################################################
### CUSTOM last_stage_postinst SCRIPT FOR DISTRO ###
####################################################
echo "Setting-up network for distro ${DISTRO}..."
if ! [ "$DISTRO" = "netbsd" -o "$DISTRO" = "xenhvm" -o "$DISTRO" = "centos" -o "$DISTRO" = "neoshine" -o "$DISTRO" = "debian" -o "$DISTRO" = "debian-dtc" ] ; then
	if [ -x /usr/share/dtc-xen-os/${DISTRO}/last_stage_custom ] ; then
		/usr/share/dtc-xen-os/${DISTRO}/last_stage_custom ${FW_PARAMS}
	fi
fi


#######################
### UMOUNT AND EXIT ###
#######################
if ! [ "${VIRT_TYPE}" = "vz" -o "$DISTRO" = "netbsd" -o "$DISTRO" = "xenhvm" ] ; then
	echo "Unmounting proc and filesystem root..."
	$UMOUNT ${VPSGLOBPATH}/${VPSNUM}/proc 2> /dev/null || /bin/true
	$UMOUNT ${VPSGLOBPATH}/${VPSNUM}
fi
echo "Install script finished: click on the installation tab on the left to refresh!"
exit 0
