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

# check distro
DISTRO=`/usr/lib64/lxcf/lxcf-distro`

# 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_I=0 ; HOSTNAME=""
FLG_P=0 ; PASSWORD=""


while getopts i:p: OPT ; do
  case $OPT in
  i) FLG_I=1 ; HOSTNAME=$OPTARG ;;
  p) FLG_P=1 ; PASSWORD=$OPTARG ;;
  esac
done
shift $((OPTIND - 1))

# Reading of config parameter
PROXYUSER=`egrep "^proxy-user" /etc/lxcf/lxcf.conf | \
	awk '{print $1}' | awk -F '=' '{print $2}'`
PROXYNAME=`egrep "^proxy" /etc/lxcf/lxcf.conf | egrep -v "proxy-user" | \
	awk '{print $1}' | awk -F '=' '{print $2}'`
NOPROXY=`egrep "^noproxy" /etc/lxcf/lxcf.conf | \
	awk '{print $1}' | awk -F '=' '{print $2}'`

PROXYARGS=""
if [ x$PROXYUSER != x"" ]; then
	PROXYARGS=${PROXYARGS}" -u "$PROXYUSER
fi
if [ x$PROXYNAME != x"" ]; then
	PROXYARGS=${PROXYARGS}" -x "$PROXYNAME
fi
if [ x$NOPROXY != x"" ]; then
	PROXYARGS=${PROXYARGS}" --noproxy "$NOPROXY
fi

if [ $FLG_I -eq 1 ]; then
	ARG=`echo $* | sed 's% %/%g'`
	curl -s $PROXYARGS -F "password="${PASSWORD} \
		$HOSTNAME"/lxcfv1/snapshot-list/"$ARG  | \
	/usr/bin/awk 'BEGIN{f=1}{if($0~/pre/){f=f*(-1)} else if(f == -1) {print}}'  | \
	/usr/bin/awk 'BEGIN{ln=0}{if ($0!="\n") {ar[ln]=$0;ln++}} \
		END{for(i=1;i<ln;i++){print ar[i]} \
		split(ar[0],sr,"=");exit(int(sr[2]))}'
	exit $?
fi

if [ $# -eq 0 ] ; then
	LANG=c /bin/ls -lh /opt/lxcf_rep | tail -n +2 | egrep -v '^d' | \
	awk '{printf "%-20s %s\t%s %s %s\n",$9,$5,$6,$7,$8}'
else
	for i in $* 
	do
		if [ -f /opt/lxcf_rep/$i ]; then
			tar tzf /opt/lxcf_rep/$i | egrep uuid | \
			awk -F '/' \
				'BEGIN{printf "'$i' : "}\
				{printf "%s ",$2}\
				END{printf "\n"}'
		else
			echo "error: $i image is not exist"
			exit -1
		fi
	done
fi

exit 0

