#!/bin/env bash

#Author: Drew Anderson
#Purpose: Making the creation of zipped archives of VMs easier for ReAssure users
#Date: Around the beginning of July, 2006
#Version: 0.3

env_path="/bin/env" #used later-on; if yours is in a different place, you will want to change this
flag=0
usetar=0
img_dir=""
img_name=""
temp_inpt=""
start_dir=`pwd`

#if the user didn't specify any parameters, we use an interactive mode to get them
if [ -z "$1" ];
then
	flag=1 #specifies interactive mode
	echo "No parameters specified, entering interactive mode"
	echo ""
	echo "Useage for noninteractive mode: compimg.sh <directory> [<new_file_name>]"
	echo ""
fi

#if interactive mode
if [ "$flag" == 1 ];
then
	#get the image directory
	echo -n "Enter image directory [.]: "
	temp_inpt=""
	read -e temp_inpt
	#echo "DEBUG: $temp_inpt"
	#if the user wants to specify a different direcotry
	if [ -n "$temp_inpt" ];#temp_inpt will be non-empty
	then
		#use it
		img_dir=$temp_inpt
	else
		#use the default
		img_dir=`pwd`
	fi
else
	#image directroy is the first parameter
	img_dir="$1"
fi

#echo "DEBUG: img_dir = $img_dir"

#the default name of the image is derived from the directory name
img_name=$img_dir;

img_name=`basename "$img_name"`

#if we are in interactive mode
if [ "$flag" == 1 ];
then
	#ask the user what the output filename ought to be
	echo -n "What should the output filename be? [$img_name]: "
	temp_inpt=""
	read -e temp_inpt
	
	#if the user didn't accept the default name
	if [ -n "$temp_inpt" ];#-n for nonempty
	then
		#we use his/hers
		img_name=$temp_inpt
	fi
fi

temp_inpt=`$env_path zip -h 2>&1`

if [ $? == 127 ] #the exit code is set to 127 (failure)
then
	echo -n "zip executable not found, checking for tar..."
	
	temp_inpt=`$env_path tar 2>&1`
	
	if [ "$?" == 127 ]
	then
		echo " tar executable not found"
		usetar=2
	else
		echo " found tar"
		echo -n "checking for gzip..."

		temp_inpt=`$env_path gzip -h 2>&1`
		
		if [ "$?" == 127 ]
		then
			echo " gzip executable not found"
			usetar=2
		else
			echo " found gzip"
			usetar=1
		fi
	fi
fi

cd $img_dir

if [ "$usetar" == 0 ]
then
	echo "Archive name will be \"$img_name.zip\" and the file will be created in $start_dir ($start_dir/$img_name.zip)"
	$env_path zip -9 -T $start_dir/$img_name.zip *.vmdk *.vmx *.vmsd *.nvram *.vmss *.vmem
	echo "Done!"
else 
	if [ ! "$usetar" == 2 ] # 2 is our failure mode since it was next after 1 :)
	then
		echo "Archive name will be \"$img_name.tar.gz\" and the file will be created in $start_dir ($start_dir/$img_name.tar.gz)"
		$env_path tar -cf $start_dir/$img_name.tar *.vmdk *.vmx *.vmsd *.nvram *.vmss *.vmem
		$env_path gzip --best $start_dir/$img_name.tar
		echo "Done!"
	else
		echo "Sorry, but the required binaries were not found on the system."
	fi
fi

echo " "
