#!/bin/sh
# copyright (C) 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 root
if [ ${EUID:-${UID}} != 0 ]; then
    echo "error: Because you are not root, you cannot execute this command. "
    exit 1
fi

# check option
FLG_F=0

while getopts f OPT ; do
  case $OPT in
  f) FLG_F=1 ;;
  esac
done
shift $((OPTIND - 1))

# check args
if [ ! $# -eq 2 ]; then
	echo "usage: lxcf snapshot [ -f ] (LXCF_UUID | NAME)  PATH"
	exit 1
fi

LXCF_UUID=$1
CONTPATH=`cd $2;pwd`

lsdir() {
  ls -f --ind=none $1 | sed '/^\.\{1,2\}$/d'
}

# find LXCNAME from UUID
LXCNAME=""
for i in `lsdir /etc/lxcf/rsc`
do
	if [ $LXCF_UUID == $i ]; then
		LXCNAME=$i
		LXCF_UUID=`cat /etc/lxcf/rsc/$i/uuid`
		break
	fi
	if [ $LXCF_UUID == `cat /etc/lxcf/rsc/$i/uuid` ]; then
		LXCNAME=$i
		break
	fi
done

if [ -z $LXCNAME ]; then
  echo "error:" $LXCF_UUID "is the unknown container UUID"
fi

if [ ! -d ${CONTPATH} ] ; then
  echo "error:" $CONTPATH "is the unknown path"
  exit 1
fi

# take the snapshot
LPWD=$PWD

mkdir -p ${CONTPATH}/${LXCF_UUID}

cd /opt/lxcf
/usr/bin/tar czf ${CONTPATH}/${LXCF_UUID}/snapshot.tgz ${LXCNAME} >& /dev/null
cp -pr /etc/lxcf/rsc/${LXCNAME}  ${CONTPATH}/${LXCF_UUID}/
echo -n ${LXCNAME} > ${CONTPATH}/${LXCF_UUID}/name
LANG=C yum list installed | \
	awk 'BEGIN{f=0}{if(f==1)print $1;if($1=="Installed")f=1}' \
		>  ${CONTPATH}/${LXCF_UUID}/pkg.info

cd ${CONTPATH}
if [ -e "${LXCF_UUID}_${LXCNAME}.img" -a $FLG_F -eq 0 ]; then
	echo "error: file exists :" ${LXCF_UUID}_${LXCNAME}.img
	exit 1
fi

/usr/bin/tar czf "${LXCF_UUID}_${LXCNAME}.img" ${LXCF_UUID} >& /dev/null

rm -rf ${LXCF_UUID}

cd $LPWD

exit 0


