#!/bin/sh

# **************************** LICENSE START ***********************************
#
# Copyright 2013 ECMWF and INPE. This software is distributed under the terms
# of the Apache License version 2.0. In applying this license, ECMWF does not
# waive the privileges and immunities granted to it by virtue of its status as
# an Intergovernmental Organization or submit itself to any jurisdiction.
#
# ***************************** LICENSE END ************************************

set -x 

print_err()
{
	echo ${text_ERR}  $* >> "${f_LOG}"
} 

print_warn()
{
	echo "WARNING: "  $* >> "${f_LOG}"
} 

text_ERR="ERROR: script `basename $0` FAILED! "

#The original version of this function was taken from: 
#http://stackoverflow.com/questions/12340846/bash-shell-script-to-find-the-closest-parent-directory-of-several-files
function findCommonPath()
{
  	var1=$1
  	var2=$2
  	path="/"
  	prev_IFS=$IFS; 
	IFS="/"
  	for item in $var2; do
		test "$path" = "/" && v="$item" || v="$path/$item"
    		case $var1 in
      			$v*) ;;
      			*) break ;;
    		esac
    		path=$v
  	done
  	IFS=$prev_IFS
  	echo $path
}

#--------------------------------------------------------------------
# Read arguments. 
# Getopts has problems on some HP systems so we need to use this
# argument parsing techinque.
#--------------------------------------------------------------------

f_RES=""
f_DUMP=""
METHOD=""
f_LOG=""
useFixedName=0
retVal=0

while [ "$1" != "" ]
do
	case "$1" in

		-f)
			f_RES=$2
			useFixedName=1
			shift
			;;
		-d)
			f_DUMP=$2
			shift
			;;
		-m)
			METHOD=$2
			shift
			;;
		-l)     
			f_LOG=$2
			shift
			;;
		*) 
			break;
			;;
	
	esac	
	shift
done


if [  $# -eq 0 ] ; then
	print_err "No icons specified!"
	exit 1
fi

#--------------------------------
# Set compress cmd
#--------------------------------

case $METHOD in
	tgz) 
		COMPRESS_CMD="gzip -c"
		SUFFIX="tar.gz"
		;;
	tbz)
		COMPRESS_CMD="bzip2 -c"
		SUFFIX="tar.bz2"
		;;	
	tar)	
		COMPRESS_CMD=""
                SUFFIX="tar"
		;;
	tzip)
		COMPRESS_CMD="zip -r" 
                SUFFIX="tar.zip"
		;;
	*)
		print_err "No method is specified (via the -m flag)!"
		exit 1
		;;
esac

#Checks
if [ x"$f_LOG" = x  ] ; then
	f_LOG="/dev/null"
fi

#Clear log file
> "$f_LOG"

#tmp files
f_TMP0=/tmp/$$.0
f_TMP1=/tmp/$$.1

#Clean tmp files
rm -f /tmp/$$.*

#All path will be relative to the metview root dir
cd $METVIEW_USER_DIRECTORY

#--------------------------------------------------
# Calls mvimport for the icons to be compressed. 
# this will find all the linked and embedded icons!	
#--------------------------------------------------

#find out first
if [ x"$f_RES" = x ] ;then
	f_RES="$METVIEW_USER_DIRECTORY""/""$1""."$SUFFIX
fi

MVIMPORT_TAG="@@COMPRESS-TAG@@ " 
export MVIMPORT_TAG

for n
do
	echo "$n" 
        $METVIEW_BIN/mvimportDesktop "$n" ${f_TMP0} >/dev/null 2>&1
	if [ $? -eq 0 -a -f ${f_TMP0} ] ; then
		grep "^$MVIMPORT_TAG" ${f_TMP0} >> ${f_TMP1}
	else
		print_warn "Could not import icon \"$n\" !"
		retVal=255
	fi
> ${f_TMP0}
done


if [ ! -s ${f_TMP1} ] ; then
	print_err "No icons could be imported!"
	exit 1
fi
 
#Add "./" to the beginning of files
sed "s,$MVIMPORT_TAG,./," < ${f_TMP1} | sed "s,//,/,g" | sort -u > ${f_TMP0}


#------------------------------------------
# Find the common parent of all the icons
#------------------------------------------

d_COMMON=""
folders=""
while read m ; do

	[ x"$m" = x ] && continue

	d=`dirname "$m"` # | sed "s,//,/,g"`
			
	if [ x"${d_COMMON}" = x ] ; then 
		d_COMMON=$d
		folders=$d
	fi

	if [ `echo $folders | grep -c ${d}` -eq 0 ] ; then
		folders="${folders} $d"
		d_COMMON=$(findCommonPath "$d_COMMON" "$d")
		fi
done < ${f_TMP0} 

echo "common path " $d_COMMON

if [ x"$d_COMMON" = x  -o ! -d "$d_COMMON" ] ; then
	print_err "Failed to find common parent folder!"
	exit 1
fi 

#------------------------------------------------
# Tar up the files. 
# We will use variable folders again! First
# round create (x=c), then add/replace (x=r)	
#------------------------------------------------

cd "$d_COMMON"

tarFlag="c"
folders=""

while read m
do
	[ x"$m" = x ] && continue

	# build icon file and dot file names
	d=`dirname "$m"`
	if [ x"$d_COMMON" != x -a "$d_COMMON" != "./" ] ; then
		d=`echo "$d" | sed "s,${d_COMMON},./,g" |  sed "s,//,/,g"`		
	fi
	b=`basename "$m"`
		
	#Icon file		
	f_ICON=` echo ${d}"/"${b} | sed "s,//,/,g"`
	      
	#Dot file			
	f_DOT=`echo "${d}/._mv_iconlist_" | sed "s,//,/,g"`
	if [ ! -f "$f_DOT" ] ; then		
		f_DOT=`echo "${d}/.${b}" | sed "s,//,/,g"`
	elif [ `echo $folders | grep -c ${d}` -eq 0 ] ; then
		folders="${folders} $d"
	else	
		f_DOT=""
	fi

	if [ -e "$f_ICON" ] ; then

		if [ x"$f_DOT" != x -a -f "$f_DOT" ] ; then
			tar ${tarFlag}f ${f_TMP1} "$f_DOT" "$f_ICON"
		else
			tar ${tarFlag}f ${f_TMP1} "$f_ICON"				
		fi

		tarFlag="r"
	fi

	echo $f_ICON
	echo $f_DOT
	echo $folders

done < ${f_TMP0} 

#-- Dump the contents of the tar file
if [ x"$f_DUMP" != x ] ; then
    tar -tvf  ${f_TMP1} > "$f_DUMP"
fi

#-- Compress tmp tar file
if [  x"$COMPRESS_CMD" != x ] ;then 
	if [ "$METHOD" = "tzip" ] ; then
		eval "${COMPRESS_CMD} \"$f_RES\" ${f_TMP1}"
	else
     		eval "${COMPRESS_CMD} ${f_TMP1} > \"$f_RES\""
	fi
else
    	mv ${f_TMP1} "$f_RES"
fi

#Clean tmp files
rm -f /tmp/$$.*

exit $retVal


