#!/usr/bin/perl
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

use Carp;
use RDFStore::Model;
use RDFStore::NodeFactory;
use DBI;

my $Usage =<<EOU;
Usage is:

    $0 <querystring_or_filename> [-storename <IDENTIFIER>] [-serialize <syntax>] [-h]

Query an existing RDFStore database.

<querystring_or_filename>

		A SPARQL query string (see syntax at http://www.w3.org/TR/rdf-sparql-query/) or a file containing the actual query

		Example RSS-1.0 query

		PREFIX   rdf:   <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
		PREFIX   rss:   <http://purl.org/rss/1.0/>
		SELECT
			?title ?link
		FROM
			<http://xmlhack.com/rss10.php>
		WHERE
			( ?item rdf:type rss:item )
			( ?item rss::title ?title )
			( ?item rss::link ?link )

[-storename <IDENTIFIER>]
	If not specified into the FROM clause part of the query, this option allows to specify a 
	database IDENTIFIER like rdfstore://[HOSTNAME[:PORT]]/PATH/DBDIRNAME to query

        E.g. URLs
        		rdfstore://mysite.foo.com:1234/this/is/my/rd/store/database
                        rdfstore:///root/this/is/my/rd/store/database

[-serialize rdf-for-xml | dawg-xml ]
	Result Forms - by default SELECT generates RDF/XML tabular format (http://www.w3.org/2001/sw/DataAccess/tests/result-set#) while 
	DESCRIBE or CONSTRUCT queries generate canonical RDF/XML output.
	
	Alternatively this option allows you to get two simple XML output formats
		* dawg-xml (http://www.w3.org/2001/sw/DataAccess/rf1/) syntax
		* rdf-for-xml (http://jena.hpl.hp.com/~afs/RDF-XML.html)

[-smart]
	Use simple rdfs:subClassOf rdfs:subPropertyOf and owl:sameAs inferencing

[-comment <STRING>]
	Comment to add to the XML output

[-metadata <filename_or_URI>]
	Additional metadata link for <head/> elemenet into DAWG-XML format

[-h]
	Print this message

EOU

# Process options
print $Usage and exit if ($#ARGV<0);

my ($verbose,$metadata, $comment,$query,$storename,$input_dir,$dbms_host,$dbms_port,$serialize,$smart);
$smart=0;
while (defined($ARGV[0])) {
    my $opt = shift;

    if ($opt eq '-storename') {
        $storename = shift;
    } elsif ($opt eq '-h') {
        print $Usage;
        exit;
    } elsif ($opt eq '-smart') {
	$smart=1;
    } elsif ($opt eq '-v') {
	$verbose=1;
    } elsif ($opt eq '-input_dir') {
	$opt=shift;
	$input_dir = $opt
                if(-e $opt);
        $input_dir .= '/'
                unless( (not(defined $input_dir)) ||
                        ($input_dir eq '') ||
                        ($input_dir =~ /\s+/) ||
                        ($input_dir =~ /\/$/) );
    } elsif ($opt eq '-dbms_host') {
        $dbms_host = shift;
    } elsif ($opt eq '-dbms_port') {
	$opt=shift;
        $dbms_port = (int($opt)) ? $opt : undef;
    } elsif ($opt eq '-serialize') {
        $serialize = shift;
	$serialize = 'RDF/XML'
		unless($serialize);
    } elsif ($opt eq '-comment') {
        $comment = shift;
    } elsif ($opt eq '-metadata') {
        $metadata = shift;
    } else {
	$query=$opt;
    	};
};

my $factory = new RDFStore::NodeFactory();
my %results_options = (
	'syntax' => $serialize
	);
$results_options{'metadata'} = $metadata
	if($metadata); #check if file or URI perhaps?

$results_options{'comment'} = $comment
	if($comment);

my $dbh = DBI->connect("DBI:RDFStore:database=$input_dir$storename;host=$dbms_host;port=$dbms_port", "pincopallino", 0,
						{	nodeFactory => $factory,
							results => \%results_options,
							smarter => $smart } )
	or die "Oh dear, can not connect to rdfstore: $!";

if( -e $query && -r _ ) {
	open(QUERY, $query);
	$query='';
	while(<QUERY>) {
		$query.=$_;
		};
	close(QUERY);
	};

my $sth;
my $rdfresults;
eval {
        $sth=$dbh->prepare($query);
	$sth->execute();
	};
my $err = $@;
croak $err
	if $err;

if( $sth->func('getQueryStatement')->getQueryType eq 'SELECT' and $serialize !~ /n-triples/i ) {
	while (my $xml = $sth->func( $serialize ? $serialize : 'dawg-results', 'fetchrow_XML' )) {
		print $xml;
       		};
} else {
	while (my $rdf = $sth->func( $serialize ? $serialize : 'RDF/XML', 'fetchsubgraph_serialize' )) {
		print $rdf;
       		};
	};

$sth->finish();
