#!/bin/bash

if [ $# -ne 9 ] ; then
        echo "Usage: $0 <CTID> <OSTEMPLATE> <RAM_GB> <DISK_GB> <CPUs> <IP> <NETMASK> <GW> <FQDN>"
        echo " OSTEMPLATE: centos-6-x86_64 debian-3.1-x86"
        exit 1
fi

CTID="$1"
OSTEMPLATE="$2"
RAM_GB="$3"
DISK_GB="$4"
CPUS="$5"
IP="$6"
NETMASK="$7"
GW="$8"
FQDN="$9"
HOSTNAME="$(echo $FQDN |awk -F '.' '{print $1}')"
DOMAIN="$(echo $FQDN |sed -e "s/$HOSTNAME\.//")"

vzctl create $CTID --ostemplate $OSTEMPLATE --config vswap-1g

vzctl set $CTID --save --name $HOSTNAME
vzctl set $CTID --save --onboot yes
vzctl set $CTID --save --hostname $FQDN
vzctl set $CTID --save --netif_add eth0,,,FE:FF:FF:FF:FF:FF
vzctl set $CTID --save --searchdomain $DOMAIN
vzctl set $CTID --save --nameserver 8.8.8.8 --nameserver 8.8.4.4
vzctl set $CTID --save --cpus $CPUS
vzctl set $CTID --save --ram ${RAM_GB}G
vzctl set $CTID --save --swap 4G
vzctl set $CTID --save --diskspace ${DISK_GB}G
vzctl start $CTID
vzctl exec $CTID passwd

if [ ${OSTEMPLATE:0:6} = "debian" ] ; then

        cat << _EOF_ > /vz/root/$CTID/etc/network/interfaces
auto lo eth0
iface lo inet loopback
iface eth0 inet static
        address $IP
        netmask $NETMASK
        gateway $GW
_EOF_  

        vzctl exec $CTID /etc/init.d/networking restart

else

        cat << _EOF_ > /vz/root/$CTID/etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE="eth0"
HOSTNAME="$HOSTNAME"
IPV6INIT="no"
MTU="1500"
TYPE="Ethernet"
ONBOOT=yes
BOOTPROTO=static
IPADDR=$IP
NETMASK=$NETMASK
GATEWAY=$GW
_EOF_

        vzctl exec $CTID /etc/init.d/network restart

fi
