#!/bin/bash
# @package      hubzero-mw2-exec-service
# @file         mkvztemplate
# @author       Pascal Meunier <pmeunier@purdue.edu>
# @copyright    Copyright (c) 2016-2017 HUBzero Foundation, LLC.
# @license      http://opensource.org/licenses/MIT MIT
#
# Based on previous work by Richard L. Kennell and Nicholas Kisseberth
#
# Copyright (c) 2016-2017 HUBzero Foundation, LLC.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# 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 [ "${ARCH}" != "i386" -a "${ARCH}" != "amd64" ]; then
	echo "Unrecognized or no architecture [${ARCH}] requested."
        echo "Usage: mkvztemplate [i386|amd64] [wheezy|lenny|squeeze] [buck|production-stable|manny]"
	exit 1
fi

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

# hubzero.org:/www/packages/deb/dists/
# name-deb#, e.g., "ellie-deb7"
# diego, ellie, production-name, shira, sid
if [ "${HUBRELEASE}" != "diego" -a "${HUBRELEASE}" != "ellie"  -a "${HUBRELEASE}" != "shira" -a "${HUBRELEASE}" != "sid" ]; then
	echo "Unrecognized or no release [${HUBRELEASE}] requested."
        echo "Usage: mkvztemplate [i386|amd64] [wheezy|lenny|squeeze] [buck|production-stable|manny]"
	exit 1
fi

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

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

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

if [ "${DEBRELEASE}" = "lenny" ]; then
	DEBVERSION=5
fi

if ! [ -d /usr/lib/debootstrap ]; then
  echo please install debootstrap
  echo exiting now
  exit 3
fi

VZROOT=/var/lib/vz
VZTEMPLATEDIR=${VZROOT}/template
MYTEMPLATE=debian-${DEBVERSION}.0-${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

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

if [ "${DEBRELEASE}" = "wheezy" ]
then
    if [ -d /usr/lib/debootstrap -a ! -f /usr/lib/debootstrap/scripts/wheezy ]
    then
            SCRIPT="/usr/lib/debootstrap/scripts/squeeze"
    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
echo "apt-key adv --keyserver keys.gnupg.net --recv-keys 143C99EF" | chroot ${MYTEMPLATEDIR}

# 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

# 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

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

#if [ "${DEBRELEASE}" = "wheezy" ]; then
echo "apt-get install -y geany libgl1-mesa-dev libglui-dev ttf-liberation" | chroot ${MYTEMPLATEDIR}
#else
#  echo "apt-get install -y libgl1-mesa-swx11-dev" | chroot ${MYTEMPLATEDIR}
#fi
echo "mkdir /usr/lib/debug/.root/; ln -s /usr/lib/debug/lib /usr/lib/debug/.root/lib" | chroot ${MYTEMPLATEDIR}
echo "cd /usr/share/fonts/truetype/msttcorefonts; mkfontdir; mkfontscale" | chroot  ${MYTEMPLATEDIR}
echo "cd /usr/share/fonts/truetype/ttf-bitstream-vera; mkfontdir; mkfontscale" | chroot ${MYTEMPLATEDIR}
echo "cd /usr/share/fonts/X11/100dpi; mkfontdir; mkfontscale" | chroot ${MYTEMPLATEDIR}
echo "cd /usr/share/fonts/X11/75dpi; mkfontdir; mkfontscale" | chroot ${MYTEMPLATEDIR}
echo "cd /usr/share/fonts/X11/misc; mkfontdir; mkfontscale" | chroot ${MYTEMPLATEDIR}
echo "cd /usr/share/fonts/truetype/freefont; mkfontdir; mkfontscale" | chroot ${MYTEMPLATEDIR}
echo "cd /usr/share/fonts/truetype/ttf-dejavu; mkfontdir; mkfontscale" | chroot ${MYTEMPLATEDIR}
echo "cd /usr/share/fonts/truetype/ttf-liberation; mkfontdir; mkfontscale" | chroot ${MYTEMPLATEDIR}
echo "cd /usr/share/fonts/truetype/unifont; mkfontdir; mkfontscale" | chroot ${MYTEMPLATEDIR}

# Configure default network for container
echo "localhost" > ${MYTEMPLATEDIR}/etc/hostname
echo "127.0.0.1       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 for compatibility when running on RedHat hosts
echo "auto lo" > ${MYTEMPLATEDIR}/etc/network/interfaces
echo "iface lo inet loopback" >> ${MYTEMPLATEDIR}/etc/network/interfaces

# Install hubzero packages needed in session containers
/bin/cat <<EOF >> ${MYTEMPLATEDIR}/etc/apt/sources.list
deb http://packages.hubzero.org/deb ${HUBRELEASE}-deb${DEBVERSION} 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}


# 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
if [ "${DEBRELEASE}" = "wheezy" ]; then
  /bin/cat << EOF > ${MYTEMPLATEDIR}/etc/rc.local
#!/bin/sh -e
# fix sshd issue with /var/run/sshd
if [ ! -d /run/sshd ]; then
  mkdir -p /run/sshd
fi
exit 0
EOF
fi

# 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

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

echo "Done."
