#!/bin/sh
#
# @package      hubzero-mw-service
# @file         mkvztemplate
# @author       Nicholas J. Kisseberth <nkissebe@purdue.edu>
# @copyright    Copyright (c) 2008-2013 HUBzero Foundation, LLC.
# @license      http://www.gnu.org/licenses/lgpl-3.0.html LGPLv3
#
# Copyright (c) 2008-2013 HUBzero Foundation, LLC.
#
# This file is part of: The HUBzero(R) Platform for Scientific Collaboration
#
# The HUBzero(R) Platform for Scientific Collaboration (HUBzero) is free
# software: you can redistribute it and/or modify it under the terms of
# the GNU Lesser General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# HUBzero is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# HUBzero is a registered trademark of HUBzero Foundation, LLC.
#

ARCH=$1
DEBRELEASE=$2
HUBRELEASE=$3

if [ `/usr/bin/id -u` != 0 ]; then echo "Must be root to make and install the maxwell openvz templates"; exit 100; fi

if [ "${DEBRELEASE}" != "etch" -a "${DEBRELEASE}" != "lenny" -a "${DEBRELEASE}" != "squeeze" -a "${DEBRELEASE}" != "wheezy" ]; then
	echo "Unrecognized or no debian release [${DEBRELEASE}] requested."
	echo "Usage: mkvztemplate [i386|amd64] [etch|lenny|squeeze|wheezy] [lenny|buck|manny|shira|sid|...]"
	exit 1
fi

if [ "${ARCH}" != "i386" -a "${ARCH}" != "amd64" ]; then
	echo "Unrecognized or no architecture [${ARCH}] requested."
	echo "Usage: mkvztemplate [i386|amd64] [etch|lenny|squeeze|wheezy] [lenny|buck|manny|shira|sid|...]"
	exit 1
fi

if [ "${HUBRELEASE}" = "" ]; then
	echo "No HUBzero release requested."
	echo "Usage: mkvztemplate [i386|amd64] [etch|lenny|squeeze|wheezy] [lenny|buck|manny|shira|sid|...]"
	exit 1
fi

if [ "${HUBRELEASE}" != "lenny" -a "${HUBRELEASE}" != "buck" -a "${HUBRELEASE}" != "manny" -a "${HUBRELEASE}" != "sid" -a "${HUBRELEASE}" != "shira" ]; then
	echo "WARNING: Unrecognized [${HUBRELEASE}] requested, continuing anyway."
fi

MIRROR="http://http.us.debian.org/debian/"
SECMIRROR="http://security.debian.org/"

if [ "${DEBRELEASE}" = "etch" ]; then
	DEBVERSION=4.0
	MIRROR="http://archive.debian.org/debian/"
	SECMIRROR="http://archive.debian.org/debian-security/"
fi

if [ "${DEBRELEASE}" = "lenny" ]; then
	DEBVERSION=5.0
	MIRROR="http://archive.debian.org/debian/"
	SECMIRROR="http://archive.debian.org/debian-security/"
fi

if [ "${DEBRELEASE}" = "squeeze" ]; then
	DEBVERSION=6.0
	EXTRA_APT="deb ${MIRROR} squeeze-updates main contrib non-free"
fi

if [ "${DEBRELEASE}" = "wheezy" ]; then
	DEBVERSION=7.0
	EXTRA_APT="deb ${MIRROR} wheezy-updates main contrib non-free"
fi

VZROOT=/var/lib/vz
VZTEMPLATEDIR=${VZROOT}/template
MYTEMPLATE=debian-${DEBVERSION}-${ARCH}-maxwell
MYTEMPLATEDIR=${VZTEMPLATEDIR}/${MYTEMPLATE}

if [ -f ${VZROOT}/template/cache/${MYTEMPLATE}.tar.gz ]; then
	echo "Template cache ${VZROOT}/template/cache/${MYTEMPLATE}.tar.gz already exists."
	exit 0;
fi

if [ ! -d ${VZTEMPLATEDIR} ]; then
	echo "Template directory does not exist: ${VZTEMPLATEDIR}"
	exit 2;
fi

if [ ! -d ${MYTEMPLATEDIR} ]; then

	mkdir -p ${MYTEMPLATEDIR}

	if [ ! -d ${MYTEMPLATEDIR} ]; then
        	echo "Unable to create template root directory: ${MYTEMPLATEDIR}"
        	exit 4;
	fi
fi

# etch's debootstrap doesn't know about squeeze. etch/lenny/squeeze seem
# to share the same support script in newer versions so we just make a link here
if [ "${DEBRELEASE}" = "squeeze" ]
then
    if [ -d /usr/lib/debootstrap -a ! -f /usr/lib/debootstrap/scripts/squeeze ]
    then
	    SCRIPT="/usr/lib/debootstrap/scripts/lenny"
    fi
fi

# etch's debootstrap doesn't know about wheezy. etch/lenny/squeeze/wheezy seem
# to share the same support script in newer versions so we just make a link here
if [ "${DEBRELEASE}" = "wheezy" ]
then
    if [ -d /usr/lib/debootstrap -a ! -f /usr/lib/debootstrap/scripts/wheezy ]
    then
	    SCRIPT="/usr/lib/debootstrap/scripts/lenny"
    fi
fi

# Make iniital debian bootstrap image
/usr/sbin/debootstrap --arch ${ARCH} --include=locales ${DEBRELEASE} ${MYTEMPLATEDIR} ${MIRROR} ${SCRIPT}

# Configure apt
/bin/cat <<EOF > ${MYTEMPLATEDIR}/etc/apt/sources.list
deb ${MIRROR} ${DEBRELEASE} main contrib non-free
deb-src ${MIRROR} ${DEBRELEASE} main contrib non-free
deb ${SECMIRROR} ${DEBRELEASE}/updates main contrib non-free
deb-src ${SECMIRROR} ${DEBRELEASE}/updates main contrib non-free
${EXTRA_APT}
EOF

# Get signing key for HUBzero repositories
wget http://packages.hubzero.org/deb/hubzero-signing-key.asc -O ${MYTEMPLATEDIR}/root/hubzero-signing-key.asc
echo "/usr/bin/apt-key add /root/hubzero-signing-key.asc" | chroot ${MYTEMPLATEDIR}
/bin/rm ${MYTEMPLATEDIR}/root/hubzero-signing-key.asc

# Remove unneeded gettys
/bin/sed -i -e '/getty/d' ${MYTEMPLATEDIR}/etc/inittab

# Disable root account
/bin/sed -i -e 's/^root::/root:!:'/g ${MYTEMPLATEDIR}/etc/shadow

# Link mtab to /proc/mounts
/bin/rm -f ${MYTEMPLATEDIR}/etc/mtab
/bin/ln -s /proc/mounts ${MYTEMPLATEDIR}/etc/mtab

# In Lenny, /dev/ lack the pty devices needed during install, so the kernel fs
# devpts needs to be mounted
if [ "${DEBRELEASE}" = "lenny" ]
then
	echo "mount -t proc none /proc" | chroot ${MYTEMPLATEDIR}
	echo "mount -t devpts devpts -o noexec,nosuid,gid=5,mode=620 /dev/pts" | chroot ${MYTEMPLATEDIR}
fi

# In Squeeze, /proc needs to be mounted for openjdk installation (!)
# Not sure about why the jdk is required now...
if [ "${DEBRELEASE}" = "squeeze" ]
then
	echo "mount -t proc none /proc" | chroot ${MYTEMPLATEDIR}
fi

# Configure locale information
/bin/cat << EOF > ${MYTEMPLATEDIR}/etc/locale.gen
en_US.UTF-8 UTF-8
en_US ISO-8859-1
EOF
echo "/usr/sbin/locale-gen" | chroot ${MYTEMPLATEDIR}

# Update package list
echo "apt-get update -y" | chroot ${MYTEMPLATEDIR}

# Temporarily install a policy-rc.d script to prevent package installation
# from running init.d scripts
/bin/cat << EOF > ${MYTEMPLATEDIR}/usr/sbin/policy-rc.d
#!/bin/sh
exit 101
EOF
/bin/chmod +x ${MYTEMPLATEDIR}/usr/sbin/policy-rc.d

# Bug in lenny packages give (probably benign) errors about missing font 
#     directory, we make link here to silence the error. Proper fix 
#     is probably a change in a configuration file somewhere to not reference 
#     those directories.
if [ "${DEBRELEASE}" = "lenny" ]
then
echo "mkdir -p /etc/X11/fonts/X11R7" | chroot ${MYTEMPLATEDIR}
echo "ln -s /usr/share/fonts/X11/Type1/ /etc/X11/fonts/X11R7/Type1" | chroot ${MYTEMPLATEDIR}
fi

# Bug in etch installation has a dependency with fontconfig that gets 
#     resolved if it is installed seperately and first
# Bug in etch packages give (probably benign) errors about missing font 
#     directories, we make links here to silence the error. Proper fix 
#     is probably a change in a configuration file somewhere to not reference 
#     those directories.
if [ "${DEBRELEASE}" = "etch" ]
then
echo "mkdir -p /usr/lib/X11/fonts" | chroot ${MYTEMPLATEDIR}
echo "mkdir -p /etc/X11/fonts/X11R7" | chroot ${MYTEMPLATEDIR}
echo "ln -s /usr/share/fonts/X11/100dpi/ /usr/lib/X11/fonts/100dpi" | chroot ${MYTEMPLATEDIR}
echo "ln -s /usr/share/fonts/X11/75dpi/ /usr/lib/X11/fonts/75dpi" | chroot ${MYTEMPLATEDIR}
echo "ln -s /usr/share/fonts/X11/cyrillic/ /usr/lib/X11/fonts/cyrillic" | chroot ${MYTEMPLATEDIR}
echo "ln -s /usr/share/fonts/X11/misc/ /usr/lib/X11/fonts/misc" | chroot ${MYTEMPLATEDIR}
echo "ln -s /usr/share/fonts/X11/Type1/ /usr/lib/X11/fonts/Type1" | chroot ${MYTEMPLATEDIR}
echo "ln -s /usr/share/fonts/X11/Type1/ /etc/X11/fonts/X11R7/Type1" | chroot ${MYTEMPLATEDIR}
echo "ln -s /usr/share/fonts/truetype /usr/lib/X11/fonts/truetype" | chroot ${MYTEMPLATEDIR}
echo "apt-get install -y fontconfig" | chroot ${MYTEMPLATEDIR}
fi

# Install openssh and basic vnc server support packages
echo "apt-get install -y vnc4server fontconfig xfonts-cyrillic xfonts-100dpi xfonts-75dpi xfonts-scalable ttf-bitstream-vera ssh openssh-server" | chroot ${MYTEMPLATEDIR}

# Bug in etch packages give (probably benign) errors about missing font 
#     directories, we make links here to silence the error. Proper fix 
#     is probably a change in a configuration file somewhere to not reference 
#     those directories.
if [ "${DEBRELEASE}" = "etch" ]; then
echo "ln -s /usr/share/fonts/truetype /usr/share/fonts/X11/truetype" | chroot ${MYTEMPLATEDIR}
echo "apt-get install -y x-ttcidfont-conf ttf-freefont unifont msttcorefonts" | chroot ${MYTEMPLATEDIR}
fi

if [ "${DEBRELEASE}" = "lenny" -o "${DEBRELEASE}" = "squeeze" ]; then
echo "apt-get install -y x-ttcidfont-conf ttf-freefont ttf-unifont ttf-mscorefonts-installer" | chroot ${MYTEMPLATEDIR}
fi

if [ "${DEBRELEASE}" = "wheezy" ]; then
echo "apt-get install -y fonts-freefont-ttf ttf-unifont ttf-mscorefonts-installer" | chroot ${MYTEMPLATEDIR}
fi

echo "if [ -d /usr/share/fonts/truetype/msttcorefonts ]; then mkfontdir /usr/share/fonts/truetype/msttcorefonts; mkfontscale /usr/share/fonts/truetype/msttcorefonts; fi" | chroot ${MYTEMPLATEDIR}
echo "if [ -d /usr/share/fonts/truetype/ttf-bitstream-vera ]; then mkfontdir /usr/share/fonts/truetype/ttf-bitstream-vera; mkfontscale /usr/share/fonts/truetype/ttf-bitstream-vera; fi" | chroot ${MYTEMPLATEDIR}
echo "if [ -d /usr/share/fonts/truetype/unifont ]; then mkfontdir /usr/share/fonts/truetype/unifont; mkfontscale /usr/share/fonts/truetype/unifont; fi" | chroot ${MYTEMPLATEDIR}
echo "if [ -d /usr/share/fonts/truetype/dejavu ]; then mkfontdir /usr/share/fonts/truetype/dejavu; mkfontscale /usr/share/fonts/truetype/dejavu; fi" | chroot ${MYTEMPLATEDIR}
echo "if [ -d /usr/share/fonts/truetype/liberation ]; then mkfontdir /usr/share/fonts/truetype/liberation; mkfontscale /usr/share/fonts/truetype/liberation; fi" | chroot ${MYTEMPLATEDIR}
echo "if [ -d /usr/share/fonts/truetype/freefont ]; then mkfontdir /usr/share/fonts/truetype/freefont; mkfontscale /usr/share/fonts/truetype/freefont; fi" | chroot ${MYTEMPLATEDIR}

# Configure default network for container
echo "localhost" > ${MYTEMPLATEDIR}/etc/hostname
echo "127.0.0.1 localhost.localdomain localhost" > ${MYTEMPLATEDIR}/etc/hosts
/bin/grep nameserver /etc/resolv.conf > ${MYTEMPLATEDIR}/etc/resolv.conf
echo "session optional pam_umask.so umask=0027" >> ${MYTEMPLATEDIR}/etc/pam.d/common-account

# add lo interface, needed by vzctl > 3.0.24 because /etc/init.d/network restart doesn't bring up lo
if ! grep -qw lo ${MYTEMPLATEDIR}/etc/network/interfaces; then
    echo "auto lo
iface lo inet loopback" >> ${MYTEMPLATEDIR}/etc/network/interfaces
fi

# Install hubzero packages needed in session containers
#     The are no middleware packages for etch, used to be installed manually
if [ "${DEBRELEASE}" != "etch" ]
then
/bin/cat <<EOF >> ${MYTEMPLATEDIR}/etc/apt/sources.list
deb http://packages.hubzero.org/deb ${HUBRELEASE} main contrib non-free
EOF
echo "apt-get update -y" | chroot ${MYTEMPLATEDIR}
echo "apt-get install -y vnc4server hubzero-mw-session hubzero-use" | chroot ${MYTEMPLATEDIR}
fi

# remove manual policy-rc.d, a hubzero-policy-rc.d package should get installed for future updates
rm -f ${MYTEMPLATEDIR}/usr/sbin/policy-rc.d

# Clean out logs, apt cache, etc...
echo "apt-get clean" | chroot ${MYTEMPLATEDIR}
rm -f ${MYTEMPLATEDIR}/root/.bash_history
rm -f ${MYTEMPLATEDIR}/var/log/bootstrap.log
rm -f ${MYTEMPLATEDIR}/var/log/dpkg.log
rm -f ${MYTEMPLATEDIR}/var/log/fontconfig.log
rm -f ${MYTEMPLATEDIR}/var/log/apt/term.log
rm -f ${MYTEMPLATEDIR}/var/log/apt/history.log
rm -f ${MYTEMPLATEDIR}/var/log/alternatives.log

# Setup ssh environments
# I don't think this is needed anymore (if ever)
#/bin/mkdir -p ${MYTEMPLATEDIR}/root/.ssh
#/bin/chmod 700 ${MYTEMPLATEDIR}/root/.ssh
#/bin/cat << EOF > ${MYTEMPLATEDIR}/etc/rc2.d/S15ssh_gen_host_keys
##!/bin/sh
#/usr/bin/ssh-keygen -f /etc/ssh/ssh_host_rsa_key -t rsa -N ''
#/usr/bin/ssh-keygen -f /etc/ssh/ssh_host_dsa_key -t dsa -N ''
#rm -f \$0
#EOF
#/bin/chmod a+x ${MYTEMPLATEDIR}/etc/rc2.d/S15ssh_gen_host_keys

# Configure time of day
/bin/cp /etc/localtime ${MYTEMPLATEDIR}/etc/localtime
/bin/cp /etc/timezone ${MYTEMPLATEDIR}/etc/timezone

# Don't print message of the day inside containers
if [ -f ${MYTEMPLATEDIR}/etc/pam.d/sshd ]
then
sed -i '/pam_motd.so/d' ${MYTEMPLATEDIR}/etc/pam.d/sshd
fi

# In Lenny, /dev/ lacks the pty devices needed during install, so the kernel fs
# devpts needs to be mounted. Unmount when we are done with it.
if [ "${DEBRELEASE}" = "lenny" ]
then
echo "/bin/umount /dev/pts" | chroot ${MYTEMPLATEDIR}
echo "/bin/umount /proc" | chroot ${MYTEMPLATEDIR}
fi

# In Squeeze, /proc was mounted for openjdk installation
if [ "${DEBRELEASE}" = "squeeze" ]
then
echo "/bin/umount /proc" | chroot ${MYTEMPLATEDIR}
fi

# Backup created image to a tarball
/bin/tar -zcf ${VZROOT}/template/cache/${MYTEMPLATE}.tar.gz -C ${MYTEMPLATEDIR} .

echo "Done."
