#!/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::NodeFactory;
use RDFStore::Model;
use DBI;

my $Usage =<<EOU;
Usage is:
    $0 [-h] [-v] -storename <IDENTIFIER> [-syntax <RDF/XML | NTriples> ]

Query an existing RDFStore database.

-h	Print this message

-storename <IDENTIFIER>
		RDFStore database name IDENTIFIER is like rdfstore://[HOSTNAME[:PORT]]/PATH/DBDIRNAME

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

[-syntax <RDF/XML | NTriples> ]
		By default is (normalized) RDF/XML - otherwise you can specify N-Triples

[-v]	Be verbose

EOU

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

my ($verbose,$syntax,$storename,$input_dir,$dbms_host,$dbms_port);
$verbose=0;
my @query;
while (defined($ARGV[0]) and $ARGV[0] =~ /^[-+]/) {
    my $opt = shift;

    if ($opt eq '-storename') {
        $storename = shift;
    } elsif ($opt eq '-syntax') {
	$syntax=shift;
    } elsif ($opt eq '-h') {
        print $Usage;
        exit;
    } 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;
    } else {
        die "Unknown option: $opt\n$Usage";
    };
};

my $factory = new RDFStore::NodeFactory();
my $model = new RDFStore::Model( Name => $storename, Host => $dbms_host, Port => $dbms_port, Mode => 'r' );

$syntax = 'RDF/XML' unless($syntax);

print "Total statements: ".$model->size."\n"
	if($verbose);

$model->serialize( *STDOUT, $syntax );

