#!/bin/bash
# SALF: Strip Adium Log Formatting

if [ -z "$1" ]; then
	echo "usage: /path/to/logs/";
	exit;
fi

# Remove trailing slash
root=`echo "$1" | sed -e 's,\(.\)/*$,\1,'`;

# Lets loop work on files with spaces in name
IFS=$(echo -en "\n\b")
total=`find $root -name '*.chatlog' | wc -l`;
let "total=$total";
count=0;
percent=0;

for path in `find $root -name '*.chatlog'`; do
	file=${path##*/};

	if [ -d $path ]; then
#		echo "Directory: $dir";
		# Remove trailing slash
		dir=`echo "$path" | sed -e 's,\(.\)/*$,\1,'`;
		base=${file%.*};
#		echo "Moving $dir/$base.xml to $root/$base.xml";
		mv "$path/$base.xml" "$root/$base.xml";
#		echo "Removing Directory $dir";
		rm -rf $dir;
#		echo "Moving $root/$base.xml back to $dir";
		mv "$root/$base.xml" "$dir";

		path=$dir;
	fi

	sender=`echo $file | cut -d" " -f1`;
	perl -pi -e 's/<div><span.+>(.*)(<\/span><\/div>)/\1/g' $path;
	perl -pi -e 's/<message sender=".*" time="(.*)">(.+) is now online.<\/message>/<status type="online" sender="$sender" time="\1"\/>/g' $path;
	perl -pi -e 's/<message sender=".*" time="(.*)">(.+) has gone offline.<\/message>/<status type="offline" sender="$sender" time="\1"\/>/g' $path;
	perl -pi -e 's/<message sender="" time="(.*)">You left the chat.<\/message>/<event type="windowClosed" time="\1"\/>/g' $path;

	let "count+=1";
	let "percent=count/total";
	echo -e "\\rprocessing: $count/$total\\c";

	# Not Ready Yet
	#perl -pi -e 's/<message sender="" time="(.*)">You left the chat by logging out or being disconnected.<\/message>/<event type="windowClosed" time="\1"\/>/g' $file;
done

# Clears the screen of the progress indicator. As if it never was there!
echo -e "\\r\\c";

