#!/bin/bash

#+++++++++++++++++++++++++++++++++++++++++++++++++++
# eSales Media Merger Script
#
# Author: Benjamin Roth
# Version: 20151112
#+++++++++++++++++++++++++++++++++++++++++++++++++++




##########################
#     CONFIG SECTION     #
##########################
SCRIPT=${BASH_SOURCE[o]}
SCRIPTPATH=`dirname $SCRIPT`/
EXPORTPATH=${SCRIPTPATH}csv/
IMPORTPATH=${SCRIPTPATH}src/


#############################
#     UTILITY FUNCTIONS     #
#############################
function progress() {
	echo -n " ..."
	#ps ax | awk '{ print $1 }' | grep -w $$ > /dev/null
	while true
	do
		echo -n "."
		sleep 3
	done
}

function run() {
	srcfile=$1
	destfile=$2
	if [ -f ${IMPORTPATH}${srcfile} ]
	then
		echo -n "Merging file $srcfile..."
		cat ${IMPORTPATH}${srcfile} >> ${EXPORTPATH}$destfile
		if [ $? -ne 0 ]
    then
      echo "ERROR: Could not merge $srcfile into $destfile!"
      exit $?
    fi

    rm ${IMPORTPATH}${srcfile}
    if [ $? -ne 0 ]
    then
      echo "ERROR: Could not delete source file $srcfile!"
      exit $?
    fi

    echo -n " done"
    echo
	else
    echo -e "Source file $srcfile not found."
	fi
}


###############
#     RUN     #
###############
if [ $1 ] && [ $2 ]
then
	run $1 $2
else
	echo "ERROR: Wrong parameter count!"
	echo "Run $0 \$srcfile \$destfile"
fi