#!/bin/sh
#
# @package      hubzero-mw-service
# @file         mkvztemplate
# @author       Nicholas J. Kisseberth <nkissebe@purdue.edu>
# @copyright    Copyright (c) 2008-2018 HUBzero Foundation, LLC.
# @license      http://opensource.org/licenses/MIT MIT
#
# Copyright (c) 2008-2018 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 [ "${DEBRELEASE}" = "etch" ]; then
    DEBMAJOR=4
elif [ "${DEBRELEASE}" = "lenny" ]; then
    DEBMAJOR=5
elif [ "${DEBRELEASE}" = "squeeze" ]; then
    DEBMAJOR=6
elif [ "${DEBRELEASE}" = "wheezy" ]; then
    DEBMAJOR=7
elif [ "${DEBRELEASE}" = "jessie" ]; then
    DEBMAJOR=8
elif [ "${DEBRELEASE}" = "stretch" ]; then
    DEBMAJOR=9
elif [ "${DEBRELEASE}" = "sid" ]; then
    DEBMAJOR=10
else
	echo "Unrecognized or no debian release [${DEBRELEASE}] requested."
	echo "Usage: mkvztemplate [i386|amd64] [etch|lenny|squeeze|wheezy|jessie|stretch|sid] [lenny|buck|manny|shira|diego|ellie|julian|crash|...]"
	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|jessie|stretch|sid] [lenny|buck|manny|shira|diego|ellie|julian|crash|...]"
	exit 1
fi

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

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

# Currently HUBRELEASE is only used when writing out the 
# apt sources.list for hubzero packages. If we use it for any
# other logic in the future the following may
# need to be changed to set something like HUBDIST

if [ "${HUBRELEASE}" = "lenny" ]; then
        EXTRA_PACKAGES="vnc4server dash xbase-clients xterm icewm hubzero-mw-session hubzero-icewm-config hubzero-icewm-themes hubzero-use hubzero-rappture-session"

	if [ ${DEBMAJOR} -ne 5 ]; then
		echo "HUBzero release '${HUBRELEASE}' is not compatible with Debian release '${DEBRELEASE}'"
		exit 1
	fi

elif [ "${HUBRELEASE}" = "buck" ]; then
        EXTRA_PACKAGES="vnc4server dash xterm icewm hubzero-icewm hubzero-icewm-captive hubzero-icewm-themes"

	if [ ${DEBMAJOR} -ne 5 ]; then
		echo "HUBzero release '${HUBRELEASE}' is not compatible with Debian release '${DEBRELEASE}'"
		exit 1
	fi

elif [ "${HUBRELEASE}" = "manny" ]; then
        EXTRA_PACKAGES="vnc4server"

	if [ ${DEBMAJOR} -ne 6 ]; then
		echo "HUBzero release '${HUBRELEASE}' is not compatible with Debian release '${DEBRELEASE}'"
		exit 1
	fi

elif [ "${HUBRELEASE}" = "shira" ]; then
        EXTRA_PACKAGES="vnc4server"

	if [ ${DEBMAJOR} -lt 6 -o ${DEBMAJOR} -gt 7 ]; then
		echo "HUBzero release '${HUBRELEASE}' is not compatible with Debian release '${DEBRELEASE}'"
		exit 1
	fi

	HUBRELEASE="shira-deb${DEBMAJOR}"

elif [ "${HUBRELEASE}" = "diego" ]; then

	EXTRA_PACKAGES="hubzero-tigervnc-server x11-xkb-utils"

	if [ ${DEBMAJOR} -lt 6  -o ${DEBMAJOR} -gt 8 ]; then
		echo "HUBzero release '${HUBRELEASE}' is not compatible with Debian release '${DEBRELEASE}'"
		exit 1
	fi

	HUBRELEASE="diego-deb${DEBMAJOR}"

elif [ "${HUBRELEASE}" = "ellie" ]; then

	EXTRA_PACKAGES="hubzero-tigervnc-server x11-apps"

	if [ ${DEBMAJOR} -lt 8 ]; then
		EXTRA_PACKAGES="${EXTRA_PACKAGES} x11-xkb-utils"
	fi

	if [ ${DEBMAJOR} -lt 6 ]; then
		echo "HUBzero release '${HUBRELEASE}' is not compatible with Debian release '${DEBRELEASE}'"
		exit 1
	fi

	HUBRELEASE="ellie-deb${DEBMAJOR}"

elif [ "${HUBRELEASE}" = "julian" ]; then

	EXTRA_PACKAGES="hubzero-tigervnc-server x11-apps"

	if [ ${DEBMAJOR} -lt 8 ]; then
		EXTRA_PACKAGES="${EXTRA_PACKAGES} x11-xkb-utils"
	fi

	if [ ${DEBMAJOR} -lt 6 ]; then
		echo "HUBzero release '${HUBRELEASE}' is not compatible with Debian release '${DEBRELEASE}'"
		exit 1
	fi

	HUBRELEASE="julian-deb${DEBMAJOR}"
fi

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

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

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

if [ "${DEBRELEASE}" = "squeeze" ]; then
	DEBVERSION=6.0
	MIRROR="http://archive.debian.org/debian/"
	SECMIRROR="http://archive.debian.org/debian-security/"
	EXTRA_APT="deb ${MIRROR} squeeze-lts main contrib non-free"
	APT_SECURE="--allow-unauthenticated"
fi

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

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

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

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

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

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

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

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

if [ -f ${VZROOT}/template/cache/${MYTEMPLATE}.tar.gz ]; then
	echo "Template ${VZROOT}/template/cache/${MYTEMPLATE}.tar.gz already exists."
	echo ""
	echo "Extracting files."
	echo ""
	/bin/tar --checkpoint=5000 -xzpf ${VZROOT}/template/cache/${MYTEMPLATE}.tar.gz -C ${MYTEMPLATEDIR}
else

echo "Building new template ${VZROOT}/template/cache/${MYTEMPLATE}.tar.gz"

# Fall back to sid support script if we don't know about release
if [ -d /usr/lib/debootstrap -a ! -f /usr/lib/debootstrap/scripts/${DEBRELEASE} ]
then
	SCRIPT="/usr/lib/debootstrap/scripts/sid"
elif [ -d /usr/share/debootstrap -a ! -f /usr/share/debootstrap/scripts/${DEBRELEASE} ]
then
	SCRIPT="/usr/share/debootstrap/scripts/sid"
fi

# older version of dpkg-deb (RHEL6) don't support xz compressed binary packages
# we can tell debootstrap to use alternative extractor (ar) support in this case
XZSUPPORT=`dpkg-deb --help | sed -n 's/.* extreme (\(xz\)).*/\1/p'`

if [ "${XZSUPPORT}" != "xz" ]
then
EXTRACTOR_OVERRIDE=--extractor=ar
fi

# Make iniital debian bootstrap image
echo "/usr/sbin/debootstrap ${EXTRACTOR_OVERRIDE} --no-check-gpg --arch ${ARCH} --include=locales,net-tools ${DEBRELEASE} ${MYTEMPLATEDIR} ${MIRROR} ${SCRIPT}"
/usr/sbin/debootstrap ${EXTRACTOR_OVERRIDE} --no-check-gpg --arch ${ARCH} --include=locales,net-tools ${DEBRELEASE} ${MYTEMPLATEDIR} ${MIRROR} ${SCRIPT}

if [ $? != 0 ]
then
    echo "debootstrap failed to run successfully"
    exit 3
fi

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

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

if [ "${DEBRELEASE}" = "squeeze" ]
then
	echo "Acquire::Check-Valid-Until \"0\";" > ${MYTEMPLATEDIR}/etc/apt/apt.conf.d/83no_check_valid_until
fi

# 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" -o  "${DEBRELEASE}" = "jessie" -o  "${DEBRELEASE}" = "stretch" -o  "${DEBRELEASE}" = "sid" ]
then
	if [ ! -d ${MYTEMPLATEDIR}/dev/pts ]
	then
		mkdir ${MYTEMPLATEDIR}/dev/pts
	fi

	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}" = "lenny" -o "${DEBRELEASE}" = "squeeze" -o "${DEBRELEASE}" = "wheezy" -o "${DEBRELEASE}" = "jessie"  -o "${DEBRELEASE}" = "stretch"  -o  "${DEBRELEASE}" = "sid" ]
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 ${APT_SECURE} -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 0755 ${MYTEMPLATEDIR}/usr/sbin/policy-rc.d

# Upgrade packages
echo "apt-get upgrade ${APT_SECURE} -y" | chroot ${MYTEMPLATEDIR}

# 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 ${APT_SECURE} fontconfig" | chroot ${MYTEMPLATEDIR}
fi

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

# Update CA Certificate store
# ca-certificates package was needed to process mscorefonts which have to be downloaded from an external site
echo "update-ca-certificates --fresh" | chroot ${MYTEMPLATEDIR}

# Debian 4
#     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.
#     Install fonts
if [ "${DEBRELEASE}" = "etch" ]; then
echo "ln -s /usr/share/fonts/truetype /usr/share/fonts/X11/truetype" | chroot ${MYTEMPLATEDIR}
echo "apt-get install -y ${APT_SECURE} x-ttcidfont-conf ttf-freefont unifont msttcorefonts" | chroot ${MYTEMPLATEDIR}
fi

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

# Debian 7|Debian 8|Debian 9|Debian 10
#     Install fonts
if [ "${DEBRELEASE}" = "wheezy" -o "${DEBRELEASE}" = "jessie" -o "${DEBRELEASE}" = "stretch" -o  "${DEBRELEASE}" = "sid" ]; then
echo "apt-get install -y ${APT_SECURE} fonts-freefont-ttf ttf-unifont ttf-mscorefonts-installer" | chroot ${MYTEMPLATEDIR}
fi

# Make font directories
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
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" >> ${MYTEMPLATEDIR}/etc/network/interfaces
    echo "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 ${APT_SECURE} " | chroot ${MYTEMPLATEDIR}
  echo "apt-get install -y ${APT_SECURE} ${EXTRA_PACKAGES} hubzero-mw-session hubzero-use" | chroot ${MYTEMPLATEDIR}
fi

# 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

# lenny
# Hotfix old lenny containers to be compatible with middleware 2 and workspace r3
if [ "${HUBRELEASE}" = "lenny" ]
then
	/bin/cp -p ${MYTEMPLATEDIR}/usr/lib/mw/bin/* ${MYTEMPLATEDIR}/usr/bin
	/bin/ln -s /usr/lib/hubzero/icewm/invoke ${MYTEMPLATEDIR}/usr/bin/icewm-hubzero
	/bin/sed -i 's#chmod 755 /var/log/mw/Xvnc#chmod 755 /var/log/mw /var/log/mw/Xvnc#' ${MYTEMPLATEDIR}/usr/bin/startxvnc
	/bin/sed -i 's#chmod 755 /var/run/mw/Xvnc#chmod 755 /var/run/mw /var/run/mw/Xvnc#' ${MYTEMPLATEDIR}/usr/bin/startxvnc
	/bin/sed -i 's#chmod 755 /var/lib/mw/Xvnc#chmod 755 /var/lib/mw /var/lib/mw/Xvnc#' ${MYTEMPLATEDIR}/usr/bin/startxvnc
fi

# buck
# Hotfix old buck containers to be compatible with middleware 2
if [ "${HUBRELEASE}" = "buck" ]
then
	/bin/cp -p ${MYTEMPLATEDIR}/usr/lib/hubzero/bin/* ${MYTEMPLATEDIR}/usr/bin
	/bin/sed -i 's#chmod 755 /var/log/hubzero/Xvnc#chmod 755 /var/log/hubzero /var/log/hubzero/Xvnc#' ${MYTEMPLATEDIR}/usr/bin/startxvnc
	/bin/sed -i 's#chmod 755 /var/run/hubzero/Xvnc#chmod 755 /var/run/hubzero /var/run/hubzero/Xvnc#' ${MYTEMPLATEDIR}/usr/bin/startxvnc
	/bin/sed -i 's#chmod 755 /var/lib/hubzero/Xvnc#chmod 755 /var/lib/hubzero /var/lib/hubzero/Xvnc#' ${MYTEMPLATEDIR}/usr/bin/startxvnc
fi

# diego-deb8
# Change default shell of user nobody to /bin/sh
if [ "${HUBRELEASE}" = "diego-deb8" ]
then
	echo "chsh -s /bin/sh nobody" | chroot ${MYTEMPLATEDIR}
fi

# Debian 8|Debian 9
# override systems that use systemd with sysvinit.

if [ "${DEBRELEASE}" = "jessie" -o "${DEBRELEASE}" = "stretch"  -o  "${DEBRELEASE}" = "sid" ]
then
	/bin/echo -e 'Package: systemd\nPin: release *\nPin-Priority: -1' > ${MYTEMPLATEDIR}/etc/apt/preferences.d/55systemd
	echo "apt-get install -y ${APT_SECURE} sysvinit-core" | chroot ${MYTEMPLATEDIR}

	if [ "${DEBRELEASE}" = "jessie" ]
	then
		echo "apt-get purge -y ${APT_SECURE} systemd" | chroot ${MYTEMPLATEDIR}
	fi

	if [ "${DEBRELEASE}" = "stretch" -o "${DEBRELEASE}" = "sid" ]
	then
		echo "apt-get purge -y ${APT_SECURE} systemd systemd-shim cgmanager" | chroot ${MYTEMPLATEDIR}
	fi
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 packages, logs, apt cache, etc...
echo "apt-get autoremove -y ${APT_SECURE} " | chroot ${MYTEMPLATEDIR}
echo "apt-get clean ${APT_SECURE} " | 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

# Unmount /dev/pts from template if it was mounted
#     /dev/pts may have been mounted in template due to
#     warning errors during apt installs

if  mountpoint ${MYTEMPLATEDIR}/dev/pts > /dev/null
then
	echo "/bin/umount /dev/pts" | chroot ${MYTEMPLATEDIR}
fi

# Unmount /proc from template if it was mounted
#     /proc may have been mounted in template to allow 
#     openjdk installation

if  mountpoint ${MYTEMPLATEDIR}/proc > /dev/null
then
	echo "/bin/umount /proc" | chroot ${MYTEMPLATEDIR}
fi

# Umount /sys from template if it was mounted
#     /sys was found to be mounted during
#     an AWS CloudFormation based build.
#     It is unclear how this happens.

if  mountpoint ${MYTEMPLATEDIR}/sys > /dev/null
then
	echo "/bin/umount /sys" | chroot ${MYTEMPLATEDIR}
fi

# Remove unneeded gettys
if [ -f ${MYTEMPLATEDIR}/etc/inittab ]
then
	/bin/sed -i -e '/^[3456789]:/d' ${MYTEMPLATEDIR}/etc/inittab
fi

# Debian 8|Debian 9
# udev should not run in openvz containers. if we don't turn
# it off the system will hit a 15 second mandatory sleep
# before continuing to boot
#
# Device permissions aren't initialized appropriately.
# Normally udev would fix this but the udev service is not
# run in containers

if [ "${DEBRELEASE}" = "jessie" -o "${DEBRELEASE}" = "stretch"  -o  "${DEBRELEASE}" = "sid" ]
then
	if [ "${DEBRELEASE}" = "jessie" ]
	then
		echo "/sbin/insserv -r udev-finish" | chroot ${MYTEMPLATEDIR}
	fi

	echo "/sbin/insserv -r udev" | chroot ${MYTEMPLATEDIR}

	/bin/cat <<EOF > ${MYTEMPLATEDIR}/etc/rc.local
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#

# Containers don't run udev which would normally
# reset device permissions appropriately.
# In particular /dev/tty and /dev/ptmx
# need to be set correctly

chmod 0666 /dev/tty
chmod 0666 /dev/ptmx
chmod 0620 /dev/tty0
chmod 0620 /dev/tty7
chmod 0620 /dev/tty8
chmod 0620 /dev/tty9
chmod 0620 /dev/tty10
chmod 0620 /dev/tty11
chmod 0620 /dev/tty12
chgrp 5 /dev/tty0
chgrp 5 /dev/tty7
chgrp 5 /dev/tty8
chgrp 5 /dev/tty9
chgrp 5 /dev/tty10
chgrp 5 /dev/tty11
chgrp 5 /dev/tty12

exit 0

EOF
	chmod 0755 ${MYTEMPLATEDIR}/etc/rc.local
fi

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

fi

echo ""
echo "Configuring template."
echo ""

/bin/grep nameserver /etc/resolv.conf > ${MYTEMPLATEDIR}/etc/resolv.conf

# Configure time of day
if [ -f /etc/timezone ]; then
  /bin/cp /etc/timezone ${MYTEMPLATEDIR}/etc/timezone
elif [ -f /etc/sysconfig/clock ]; then
  cat /etc/sysconfig/clock | sed -n -e 's/^\([ ]*ZONE[ ]*=[ ]*"\)\(.*\)\("\).*$/\2/p' > ${MYTEMPLATEDIR}/etc/timezone
fi

echo "dpkg-reconfigure --frontend noninteractive tzdata"  | chroot ${MYTEMPLATEDIR}

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


# Upgrade packages
echo "apt-get upgrade -y ${APT_SECURE} " | chroot ${MYTEMPLATEDIR}

echo ""
echo "Done."
echo ""
