#!/bin/bash

set -x

echo 1 > /proc/sys/net/ipv4/conf/all/arp_notify
echo 1 > /proc/sys/net/ipv4/conf/default/arp_notify

echo "Loading drivers"
/usr/sbin/modprobe vmxnet3

MOUNTPOINT="/mnt/containerfs"

mkdir -p /mnt/containerfs

echo "Waiting for rootfs"
while [ ! -e /dev/disk/by-label/containerfs ]; do :;done
if mount -t ext4 /dev/disk/by-label/containerfs ${MOUNTPOINT}; then
    # ensure mountpoint exists
    mkdir -p ${MOUNTPOINT}/.tether

    # ensure that no matter what we have access to required devices
    # WARNING WARNING WARNING WARNING WARNING
    # if the tmpfs is not large enough odd hangs can occur and the ESX event log will
    # report the guest disabling the CPU
    mount -t tmpfs -o size=64m tmpfs ${MOUNTPOINT}/.tether/

    # enable full system functionality in the container
    echo "Publishing modules within container"
    mkdir -p ${MOUNTPOINT}/lib/modules
    cp -pr /lib/modules/* ${MOUNTPOINT}/lib/modules/

    # switch to the new root
    echo "prepping for switch to container filesystem"

    cp /bin/tether ${MOUNTPOINT}/.tether/tether

    until [[ $(ls -1 /dev/disk/by-label | wc -l) -eq $(ls -1 /sys/block | wc -l) ]]; do sleep 0.1;done

    echo "switching to the new mount"
    systemctl switch-root ${MOUNTPOINT} /.tether/tether 2>&1
else
    # TODO: what do we do here? we really need to somehow report an error
    # fail hard
    echo "Unable to chroot into container filesystem"
fi

# Shut the system down
systemctl poweroff
