#! /bin/bash
# Usage ./preparedcss <file>

DEBUGON="FALSE"

# Echo the parameters if DEBUGON is true
debugecho() {
	if [ "$DEBUGON" = "TRUE" ]; then
		echo $1
	fi
}

# Check Script Usage
if [ $# = 0 ]
then
	debugecho "Usage: ./preparedcss <file>"
	exit 1
fi

DMOTEMP="dmotemp"
DMOSIZE="dmosize.txt"
DMOFILE=$1

# Check if the File Exists, exit if not
if [ -e "$DMOFILE" ]; then
	# Find the total number of lines in file
	nrow=`wc -l $DMOFILE | awk '{print $DMOFILE}'`
	debugecho "$DMOFILE has $nrow rows"

	# Erase an old temp directory if it exists
	rm -rf $DMOTEMP
	rm -rf $DMOSIZE
	
	# Create a temp directory
	mkdir $DMOTEMP

	# read a line from the file
	cat $DMOFILE | \
	while read line
	do

	# parse the filename and copyas name
	filename=`echo $line | (read field1 field2; echo $field1)`
	copyname=`echo $line | (read field1 field2; echo $field2)`
	debugecho "copy $filename as $copyname"

	# if the file exists, copy the file as copyname in the temp directory
	if [ -e "$filename" ]; then 
		debugecho "file $filename exists"
	
		# Extract the copy file name 
		copyfile=`basename $copyname`
		debugecho "copy file = $copyfile"

		# Extract the copy file path
		copypath=`dirname $copyname`
		debugecho "copy path = $copypath"

		# Reverse the path name ex - path/to/file will become file/to/path
	        while [ $copypath != '/' -a $copypath != '.' ] 
		do
		        # extract the base and directory names of the copyname
			copybase=`basename $copypath`
			debugecho "copy base = $copybase"
	
			copypath=`dirname $copypath`
			debugecho "copy path = $copypath"
			
			# Append the basename to the end of "revpath"
			revpath="$revpath/$copybase" 
			debugecho "revpath = $revpath"
 		done

		# Traverse the reversed path and make the directories
		currentpath=$DMOTEMP
		while [ $revpath != '/' -a $revpath != '.' ]
		do
			currentdir=`basename $revpath`
			debugecho "currentdir = $currentdir"

			currentpath="$currentpath/$currentdir"
			debugecho "currentpath = $currentpath"

			revpath=`dirname $revpath`
			debugecho "new revpath = $revpath"

			if [ -e "$currentpath" ]; then
				debugecho "directory $currentpath already exists"
			else
				debugecho "directory $currentpath does not exists"
				mkdir $currentpath
				debugecho "created $currentpath"
			fi
		done

		# Finally, copy the file to the requested directory
		cp -r $filename $DMOTEMP/$copyname
		debugecho "copied file"
	else
		debugecho "file $filename does not exist"
	fi
	
	done #end while read line
	
	# determine the size of the temp directory
	size=`du -sk $DMOTEMP | (read s f; echo $s)`
	
	# Write the size to a file
	echo $size > dmosize.txt

else
	debugecho "file $DMOFILE does not exist"
	exit 4
fi
	
exit $?
