#!/bin/bash
# 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.

VAL_PREFIX="/opt/lxcf"

# check root
if [ ${EUID:-${UID}} != 0 ]; then
    echo "error: Because you are not root, you cannot execute this command. "
    exit 1
fi

# check options
FLG_F=0 
FLG_S=0 

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

# check args
if [ $# -ne 1 ]; then
	echo "usage: lxcf restore [ -f ] [ -s ] SNAPSHOT_IMAGE"
	exit 1
fi

# check /opt/lxcf
mkdir -p /opt/lxcf

# check /etc/lxcf/rsc
mkdir -p /etc/lxcf/rsc

# check lxcf.conf
if [ ! -e /etc/lxcf/lxcf.conf ] ; then
  cp -p /usr/lib64/lxcf/lxcf.conf /etc/lxcf/lxcf.conf
fi

# check /etc/hosts
if [ ! -e /etc/hosts ] ; then
   echo "127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4" > /etc/hosts
   echo "::1         localhost localhost.localdomain localhost6 localhost6.localdomain6" >> /etc/hosts
fi

if [ ! -e $1 ]; then
	echo "error : The specified image does not exist:" $1
	exit 1
fi

CONTPATH=${1%/*}
if [ $CONTPATH == $1 ]; then
	CONTPATH=$PWD
fi
CONTPATH=`cd ${CONTPATH};pwd`

IMAGE=`basename $1 ".img"`

if [ ${#IMAGE} -lt 38 ]; then
	echo "error : The length of Image name is abnormal"
	exit 1
fi

LXCF_UUID=`echo $IMAGE | cut -c -36 `
LXCNAME=`echo $IMAGE | cut -c 38- `

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

# check existing LXCNAME and UUID
if [ $FLG_F -eq 0 ]; then
	for i in `lsdir /etc/lxcf/rsc`
	do
		if [ x${i} == x${LXCNAME} -o x${LXCF_UUID} == x`cat /etc/lxcf/rsc/${i}/uuid` ]; then
			echo "error : There is a container of the same name:" $LXCNAME ":" $LXCF_UUID
			exit 1
		fi
	done
else
	for i in `lsdir /etc/lxcf/rsc`
	do
		if [ x${i} == x${LXCNAME} -o x${LXCF_UUID} == x`cat /etc/lxcf/rsc/${i}/uuid` ]; then
			/usr/sbin/lxcf erase $i >& /dev/null
		fi
	done
fi

# Decompression of image
cd $CONTPATH
tar xzf ${IMAGE}.img

# check UUID
IMAGEUUID=`tar tzf ${IMAGE}.img | head -1`
if [ ! -f ${IMAGEUUID}$LXCNAME/uuid ]; then
    echo "error: snapshot image is abnormal"
    rm -rf $IMAGEUUID
    exit 1
fi
FILEUUID=`cat ${IMAGEUUID}$LXCNAME/uuid`
if [ x${LXCF_UUID}/ != x${IMAGEUUID} -o x${LXCF_UUID} != x${FILEUUID} ]; then
    echo "error: UUID of snapshot is abnormal:" $LXCF_UUID
    rm -rf $IMAGEUUID
    exit 1
fi
 
# check container name
if [ ! -f ${IMAGEUUID}/name ]; then
    echo "error: snapshot image is abnormal"
    rm -rf $IMAGEUUID
    exit 1
fi

LXCNAMES=`cat ${IMAGEUUID}/name` 
FILELXCNAME=`cat ${IMAGEUUID}/name | awk '{print $1}'`
if [ x${LXCNAME} != x${FILELXCNAME} ]; then
    echo "error: UUID of sngapshot is abnormal:" $LXCNAME
    rm -rf $IMAGEUUID
    exit 1
fi

# Check on overlapping name
EXITFLG=0
for i in $LXCNAMES
do
    if [ -e /opt/lxcf/${i} ]; then
        if [ $FLG_F -eq 0 ]; then
            EXITFLG=1
            echo "error: existing container name :" $i
	else
            /usr/sbin/lxcf erase $i >& /dev/null
        fi
    fi
done

# restore container image files
for i in $LXCNAMES
do
    mkdir -p /opt/lxcf/${i}
    tar xzf ${CONTPATH}/${LXCF_UUID}/${LXCF_UUID} -C /opt/lxcf/${i}
    if [ $LXCNAME != ${i} ]; then
	LXCF_UUID_i=`cat ${CONTPATH}/${LXCF_UUID}/$i/uuid`
	tar xzf ${CONTPATH}/${LXCF_UUID}/${LXCF_UUID_i} -C /opt/lxcf/${i}
	for j in `cat ${CONTPATH}/${LXCF_UUID}/${LXCF_UUID_i}.rm`
	do
		rm -f /opt/lxcf/$i/$j
	done
    fi
    cp -pr ${CONTPATH}/${LXCF_UUID}/${i} /etc/lxcf/rsc/.

    # create hostname
    echo ${i} > ${VAL_PREFIX}/${i}/etc/hostname

    # clone ip address
    if [ x$DISTRO == x"u" ]; then
      /usr/lib64/lxcf/lxcf-clone-setup-u ${i}
    elif [ x$DISTRO == x"f" ]; then
      /usr/lib64/lxcf/lxcf-clone-setup-f ${i}
    fi

    # create authorized_keys
    mkdir -p ${VAL_PREFIX}/${i}/root/.ssh
    chmod 700 ${VAL_PREFIX}/${i}/root/.ssh
    if [ -f /root/.ssh/lxcf_rsa.pub ]; then
        cp /root/.ssh/lxcf_rsa.pub ${VAL_PREFIX}/${i}/root/.ssh/authorized_keys
        chmod 600 ${VAL_PREFIX}/${i}/root/.ssh/authorized_keys
    fi

    /usr/lib64/lxcf/lxcf-define $i

    # check autostart mode
    if [ -e /etc/lxcf/rsc/${i}/autostart ]; then
        /usr/sbin/lxcf autostart $i
    fi

done

# The lack package is added. 
if [ $FLG_S -eq 1 ]; then
	LANG=C yum list installed |  \
		awk 'BEGIN{f=0}{if(f==1)print $1;if($1=="Installed")f=1}' \
			> ${CONTPATH}/${LXCF_UUID}/pkg.info_host
	diff -u ${CONTPATH}/${LXCF_UUID}/pkg.info_host \
		${CONTPATH}/${LXCF_UUID}/pkg.info \
	| egrep -v '\+\+' | egrep '^\+' | sed 's/^+//'  \
	| awk '{yumcmd="lxcf update yum install -y " $1 ";wait";system(yumcmd)}'
fi

rm -rf ${CONTPATH}/${LXCF_UUID}

for i in $LXCNAMES
do
    echo "restored" $i
    /usr/lib64/lxcf/lxcf-start $i
done

exit 0

