#!/usr/bin/perl
#example of inserting

use strict;
use locale;
use Search::OpenFTS::Index;
use DBI();

my ( $dbname, $PREFIX ) = '';
( $dbname, $PREFIX ) = split( ':', $ARGV[0] );

if ( $#ARGV != 0 ) {
    print "Usage:\ncat FILELIST | $0 DATABASE[:PREFIX]\n";
    exit;
}

my $dbi = DBI->connect( 'DBI:Pg:dbname=' . $dbname );
$dbi || die;

$dbi->{AutoCommit} = 0;

my $STID = 1;

my $idx = Search::OpenFTS::Index->new( $dbi, $PREFIX );
die "Create index object failed: $@" if !$idx;

my @tmp = $dbi->selectrow_array("select max(tid) from $idx->{TABLE};");
$STID = $tmp[0] + 1 if ( $#tmp >= 0 && $tmp[0] > 0 );

my $sth =
  $dbi->prepare("insert into $idx->{TABLE} ( tid, path ) values ( ? , ? );");
my ( $file, $rc, $success );
while (<STDIN>) {
    chomp;
    $file = $_;
    if ( -f $file && -T $file ) {    # check if file exists and plain
                                     # for non-english text 'use locale'
        open( INFILE, $file ) || die;
        print "$STID:$file";
        if ( $sth->execute( $STID, $file ) ) {    # insert tid,path
            $rc = $idx->index( $STID, \*INFILE );    # index
            if ( !$rc || $rc eq '0E0' ) {
                print ": INDEX FAILS:", $dbi->errstr, "\n";
                $dbi->rollback || die $dbi->errstr;
            } else {
                $dbi->commit || die $dbi->errstr;
                print ": OK\n";
                $STID++;
            }
        } else {
            $dbi->rollback;
            print ": INSERT FAILS:", $dbi->errstr, "\n";
        }
        close INFILE;
    }
}

$sth->finish;
$dbi->disconnect;
