#!/usr/bin/perl

# $Id: CyteSeer,v 1.1.2.3 2010-01-12 21:52:03 esuparno Exp $

####################################################################################
#
# Program Name: CyteSeer
# Engineer:	Erwin Suparno
# Date:		7/1/09
#
# Description:	This program is an interface to set
#		the sourceFolder value of a CyteSeer XML file and launch the CyteSeer program
#
# Installation: shell> perl -MCPAN -e shell
#		cpan> install XML::Simple
#
# Usage : ./CyteSeer <optional arg>
#	optional arg: "FULL_PATH_TO_SOURCE_FOLDER" 
#
####################################################################################

# the CyteSeer program
my $progname = "CyteSeer";
my $proghome = "/usr/local/$progname";
my $cyteSeer = "\"$proghome/$progname\"";

# the user home directory
my $userhome = `env | grep HOME | cut -d "=" -f2 | tr -d '\n'`;

# the XML file
my $path = $userhome."/CyteSeer User Data";
my $file = "_state/current.cyteXML";
my $historyfile = "_history/CyteSeerHistory";
my $xmlfile = "$path/$file";

# check whether cyteseer is installed
unless ( -e "$proghome/jilaunch" ) {
	print "CyteSeer is not found, please install it as root (superuser) and re-run this program!\n";
	exit 1;
}

sub launch_cyteseer {
	system "$cyteSeer &";
	exit 0;
}

sub set_source_folder_xml_value {

	use XML::LibXML;
  
	my $parser = new XML::LibXML;
	my $tree = $parser->parse_file( $xmlfile );
	my $root = $tree->getDocumentElement;

	# modify the sourceFolder to the new SOURCE_FOLDER
	if ( defined(@ARGV[0]) ) {
		my $SOURCE_FOLDER = @ARGV[0];
		if ( ! -d $SOURCE_FOLDER ) {
			print "\"$SOURCE_FOLDER\": $!\n";
			exit 1;
		}

		# mkdir when they have not been created
		unless ( -e "$path" ) {
			system "mkdir -p \"$path/_state\" && mkdir -p \"$path/_history\"" || print "failed creating directory: $!\n";
		} 
		@nodes1 = $root->findnodes( "/GContainer/GContainer[2]/GFilePath[1]/\@value" );
		@nodes1[0]->setValue( "$SOURCE_FOLDER" );

		# create the XML file
		open XML_FILE, '>', "$path/$file" or die "open \"$path/$file\" failed: $!\n";
			printf XML_FILE $tree->toString;
			close XML_FILE;

		# create history copy of the XML file with date and time as file name timestamp
		my $now = `date '+\%G-\%m-\%d_\%H-\%M-\%S' | tr -d '\n'`;
		system "cp -f \"$path/$file\" \"$path/_history/CyteSeer_$now\"";

		# adding a line in the history file
		open APPEND_TO_EOF, '>>', "$path/$historyfile" or die "open \"$path/$historyfile\" failed: $!\n";
		printf APPEND_TO_EOF "$SOURCE_FOLDER,,,$path/_history/CyteSeer_$now,true\n";
		close APPEND_TO_EOF;
	}
}


############################
# MAIN
############################
if ( ! set_source_folder_xml_value ) {
  exit 1;
}
launch_cyteseer
#EOF
