#!/usr/bin/perl
#Example of init new data base
use strict;

use Search::OpenFTS::Index;
use DBI();
use DBD::Pg();

my $TABLE = 'txt';

if ( $#ARGV < 0 ) {
    print
      "Usage:\n$0 DATABASE[:PREFIX]\nDon't forget to load contrib/tsearch2 !\n";
    print "Drop OpenFTS instance: $0 DATABASE[:PREFIX] [drop]\n";
    exit;
}

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

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

if ( $ARGV[1] eq 'drop' ) {
    my $idx = Search::OpenFTS::Index->new( $dbi, $PREFIX ) || die;
    $idx->drop;

    $dbi->do("drop table $idx->{TABLE};")
      || warn "Can't drop table " . $idx->{TABLE};
    $dbi->disconnect;

    exit;
}

my $TPREFIX                  = $PREFIX . "_" if ($PREFIX);
my $DICT_UNKNOWN_LEXEM_TABLE = $TPREFIX . 'fts_unknown_lexem';

$dbi->do(
    "create table ${TPREFIX}$TABLE (
     tid int not null primary key, 
     path varchar unique, 
     fts_index tsvector
        );"
  )
  || die;

{
    my $idx = Search::OpenFTS::Index->init(
        dbi             => $dbi,
        prefix          => $PREFIX,
        txttid          => ${TPREFIX} . $TABLE . '.tid',
        tsvector_field  => 'fts_index',
        ignore_id_index => [qw( 7 13 14 12 23 )],
        ignore_headline => [qw(13 15 16 17 5)],
        map             => '{ 
                \'4\'=>[1],  5=>[1], 6=>[1], 8=>[1], 18=>[1], 19=>[1], # unknown
              }',
        dict => [
            'Search::OpenFTS::Dict::PorterEng',

# example how to use snowball stemmer
#                { mod=>'Search::OpenFTS::Dict::Snowball', param=>'{lang=>"english", stop_file=>"/u/megera/app/fts/test-suite/Dict/english.stop"}' },
            {
                mod   => 'Search::OpenFTS::Dict::UnknownDict',
                param => "{table => \'$DICT_UNKNOWN_LEXEM_TABLE\'}"
            },
        ]
    );
    die "QQQ: $@" if !$idx;

    # here we could index files using method $idx->index;
    # it should be quite fast, because indices doesn't created yet

    $idx->create_index
      ;    #this function called automatically when destroy object $idx

    # grant permissions on search tables and indices to PUBLIC
    my $grant = $idx->fix_permissions();
    print
      "Permissions (select) granted on search tables and indices to PUBLIC\n"
      if ( $grant == 1 );

}
$dbi->disconnect;
