#!/bin/sh
# copyright (C) 2013-2014 FUJITSU LIMITED All Rights Reserved

# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; version 2
# of the License.
# 
# This program 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 General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  
# 02110-1301, USA.

# check separate model
#if [ -e /etc/lxcf/separate ] ; then
#  echo "Update cannot be done in the separate model"
#  exit -1
#fi

# check args
if [ $# -lt 1 ]; then
	echo "usage lxcf update COMMAND"
	exit 1
fi

# args and environment variables
UPDATECMD=$*
PREFIX=/opt/lxcf
UPDATE_RESULT=""

# save container status
LXCSTATES=`/usr/lib/lxcf/lxcf-list | awk '{if (NR >2) print}'`

# It is confirmed whether LXCF may stop all containers. 
echo -n "stop all lxcf containers (yes/no)? "
read ans
case ${ans} in
[Yy]|[Yy][Ee][Ss])
	continue ;;
[Nn]|[Nn][Oo])
	exit 1 ;;
*) 
	exit 1;;
esac

# recovery container status
check_stop_state() {
  while :
  do
	if [ -z "$*" ] ; then
		break;
	fi

	if [ x$3 = x"running" ] ; then
		/usr/lib/lxcf/lxcf-stop $1
	fi
	shift 3
  done
}

check_stop_state `echo -e ${LXCSTATES}`

# erase yum chache
yum clean packages >& /dev/null
yum clean all >& /dev/null

echo "### HOST start:" ${UPDATECMD} "###"
echo

# exec UPDATECMD
${UPDATECMD}
HOST_RESULT=$?
if [ ${HOST_RESULT} = 0 ] ; then
	UPDATE_RESULT=${UPDATE_RESULT}"HOST: Success exit code "${HOST_RESULT}"\n";
else
	UPDATE_RESULT=${UPDATE_RESULT}"HOST: exit code "${HOST_RESULT}"\n";
fi


echo
echo "### HOST end:" ${UPDATECMD} "###"
echo

for i in `ls -1 ${PREFIX}`
do
	if [ $i != ${PREFIX}/'*' ] ; then
		LXCNAME=`basename $i` ;
		if [ ! -e /opt/lxcf/${LXCNAME}/etc/lxcf ] ; then
			continue
		fi

		/usr/lib/lxcf/lxcf-update1 ${LXCNAME} ${UPDATECMD}
		URESULT=$?
		if [ ${URESULT} = 0 ] ; then
			UPDATE_RESULT=${UPDATE_RESULT}${LXCNAME}": Succes exit code "${URESULT}"\n"
		else
			UPDATE_RESULT=${UPDATE_RESULT}${LXCNAME}": exit code "${URESULT}"\n"
		fi
	fi
done

# recovery container status
check_recovery_state() {
  while :
  do
	if [ -z "$*" ] ; then
		break;
	fi

	if [ $3 = "running" ] ; then
		/usr/lib/lxcf/lxcf-start $1
	fi
	shift 3
  done
}

check_recovery_state `echo -e ${LXCSTATES}`


echo "### Update results ###"
echo -e ${UPDATE_RESULT}
echo

exit 0

