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

# check args
if [ $# -lt 1 ]; then
	echo "usage lxcf deploy [ FILENAME | DIR ] ..."
	exit 1
fi

# check options
FLG_D=0
FLG_F=0

while getopts df OPT
do
  case $OPT in
    "d" ) FLG_D=1 ;;
    "f" ) FLG_F=1 ;;
  esac
done

shift `expr $OPTIND - 1`

# check file name
check_filename() {
  if echo $1 | egrep '^/'  >& /dev/null ; then
    echo "error:" $1 "is an absolute path"
    exit 1
  fi
  if echo $1 | egrep '\.\.'  >& /dev/null ; then
    echo "error:" "path" $1 "contains '..'"
    exit 1
  fi
}

# args and environment variables
FILES=$*
PREFIX=/opt/lxcf

# delete HOST files
if [ ${FLG_D} = 1 ] && [ ${FLG_F} = 0 ] ; then
	echo -n "delete" ${FILES} " (yes/no)? "
	read ans
	case ${ans} in
	[Yy]|[Yy][Ee][Ss])
		continue ;;
	[Nn]|[Nn][Oo])
		exit 1 ;;
	*)
		exit 1;;
	esac
fi


lxcf_deploy1() {
	DISTROOT=/opt/lxcf/$1
	echo "### " `basename ${DISTROOT}` " ###"
	for j in ${FILES}
	do
		check_filename $j

		mkdir -p ${DISTROOT}${PWD};
		if [ -d $j ] ; then
			/usr/bin/rsync -a $PWD/$j/ ${DISTROOT}$PWD/$j
			echo "synchronize dir  : " $PWD/$j
		else
			/usr/bin/rsync -a $PWD/$j ${DISTROOT}$PWD
			echo "syncronize file : " $PWD/$j
		fi;
	done;
	echo
}

lxcf_deploy_delete1() {
	DISTROOT=/opt/lxcf/$1
	if [ ${DISTROOT} = "/" ]; then
		echo "### " HOST " ###"
	else
		echo "### " `basename ${DISTROOT}` " ###"
	fi

	for j in ${FILES}
	do
		/bin/rm -rf ${DISTROOT}$PWD/$j
		echo "delete : " $PWD/$j
	done;
	echo
}

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

	if [ ${FLG_D} = 0 ] ; then
		lxcf_deploy1 $i
	else
		lxcf_deploy_delete1 $i
	fi
done

# delete HOST files
if [ ${FLG_D} = 1 ] ; then
	lxcf_deploy_delete1 "/"
fi

exit 0
