#!/bin/sh

if [ "$1" = "--help" ]; then
	cat <<EOF
usage: vbuilder update -n <container>

options:
  --help  show this text

EOF
	exit 0
fi

CONTAINER=""
TMPFS=0
PKGS=""

while [ $# -gt 0 ]; do
	case $1 in
		-n|--name)
			shift
			CONTAINER=$1
			;;
	esac

	shift
done

if [ "$CONTAINER" = "" ]; then
	echo "no environment specified." >&2
	exit 1
fi

if ! lxc-info -n "$CONTAINER" >/dev/null 2>&1; then
	echo "no such container." >&2
	exit 1
fi

LIBEXECDIR="/usr/libexec/vbuilder"
CACHEDIR="/var/cache/vbuilder"
CONTAINER_PATH=/var/lib/lxc/$CONTAINER

if [ -d $CONTAINER_PATH/rootfs.lower ]; then
	ENV_ROOT=$CONTAINER_PATH/rootfs.lower
	rm -rf $CONTAINER_PATH/overlay/{upper,work}
	rm -rf /dev/shm/vbuilder/$CONTAINER
else
	ENV_ROOT=$CONTAINER_PATH/rootfs
fi

if ! lxc-wait -n $CONTAINER -t 3 -s STOPPED; then
	echo "container is busy." >&2
	exit 1
fi

VINE_RELEASE=$(chroot $ENV_ROOT cat /etc/vine-release)
if echo $VINE_RELEASE | grep -q VineSeed; then
	VERSION=VineSeed
else
	VERSION=$(echo $VINE_RELEASE | awk '{print $3;}' | sed -e 's/\..*$//')
fi

ARCH=""
if [ $(chroot $ENV_ROOT rpm -q --qf '%{arch}' coreutils) = "x86_64" ]; then
	ARCH=x86_64
else
	ARCH=i386
fi

COPY_RESOLVER=0
if [ -f /etc/resolv.conf ]; then
	COPY_RESOLVER=1
	RESTORE_RESOLVER=0
	if [ -f $ENV_ROOT/etc/resolv.conf ]; then
		mv -f $ENV_ROOT/etc/resolv.conf $ENV_ROOT/etc/resolv.conf.orig
		RESTORE_RESOLVER=1
	fi
	cp -f /etc/resolv.conf $ENV_ROOT/etc/resolv.conf
fi

mount -o bind,_netdev $CACHEDIR/$VERSION/$ARCH $ENV_ROOT/var/cache/apt

chroot $ENV_ROOT apt-get update && chroot $ENV_ROOT apt-get dist-upgrade

umount $ENV_ROOT/var/cache/apt


if [ $COPY_RESOLVER -ne 0 ]; then
	if [ $RESTORE_RESOLVER -ne 0 ]; then
		mv -f $ENV_ROOT/etc/resolv.conf.orig $ENV_ROOT/etc/resolv.conf
	else
		rm -f $ENV_ROOT/etc/resolv.conf
	fi
fi

