#!/usr/local/bin/perl
# ==================================================================
# Gossamer Links - enhanced directory management system
#
#   Website  : http://gossamer-threads.com/
#   Support  : http://gossamer-threads.com/scripts/support/
#   CVS Info : 087,071,086,086,085      
#   Revision : $Id: nph-index.cgi,v 1.38 2006/05/04 02:52:10 brewt Exp $
#
# Copyright (c) 2001 Gossamer Threads Inc.  All Rights Reserved.
# Redistribution in part or in whole strictly prohibited. Please
# see LICENSE file for full details.
# ==================================================================

# Load Time::HiRes if available for better time checking.
# Must appear here, or we get strange errors.
BEGIN { eval { require Time::HiRes; import Time::HiRes qw/time/; }; }

use strict;
use lib '/var/home/slowtwitch/slowtwitch.com/cgi-bin/articles/admin';
use Links qw/:objects/;

$| = 1;
local $SIG{__DIE__} = \&Links::fatal;
Links::init('/var/home/slowtwitch/slowtwitch.com/cgi-bin/articles/admin');
Links::init_admin();

main();

sub main {
# -------------------------------------------------------------------
# Reindexes the entire database.
#
    if (! $ENV{REQUEST_METHOD} ) {
        if (! @ARGV) {
            return usage();
        }
        else {
            if ($ARGV[0] =~ /change-driver=(\w+)/) {
                $PLG->dispatch('change_driver', \&change_driver, "$1");
            }
            elsif ($ARGV[0] =~ /reindex/) {
                $PLG->dispatch('reindex_database', \&reindex);
            }
            else {
                print "Invalid Argument: @ARGV\n";
                return usage();
            }
        }
    }
    else {
        $PLG->dispatch('reindex_database', \&reindex);
    }
}

sub usage {
# ------------------------------------------------------------------
# Print a usage summary.
#
    require GT::SQL::Search;
    my $drivers = join ",", GT::SQL::Search->available_drivers;
    print <<END_OF_USAGE;

USAGE: $0 [ --change-driver=DRIVER --reindex ]

This utility will either rebuild a search index, or allow you to switch
between different search drivers.

The following drivers are currently available:

    $drivers

To switch to a new driver, pass in the driver you want to use like:

  $0 --change-driver=MYSQL

To rebuild the search index, call:

  $0 --reindex

END_OF_USAGE

}

sub reindex {
# -------------------------------------------------------------------
# Do a database re-index.
#
    my ($s, $e, $f, $t, $in, $links, $category, $total, $found, $weights, $use_html);

# Print full header.
    $s = time();
    $t = scalar localtime;

    $use_html = $ENV{REQUEST_METHOD} ? 1 : 0;

    if ($use_html) {
        print $IN->header ( -nph => $CFG->{nph_headers} );
        print qq~
<html>
<head>
<title>Reindexing Database</title>
</head>
<body bgcolor="white">
<table border="1" cellpadding="0" cellspacing="0"><tr><td>
    <table bgColor="#ffffff" border="0" cellPadding="3" cellSpacing="3" width="500" valign="top">
      <tr>
        <td align="left" bgColor="navy"><b><font color="#ffffff" size="2" face="Tahoma,Arial,Helvetica">Reindexing Database ...</font></b></td>
      </tr>
      <tr>
        <td>
          <p align="center"><b><font color="#000000" size="2" face="Tahoma,Arial,Helvetica">Reindexing Database ...</font></b></p>
          <p><font size="2" face="Tahoma,Arial,Helvetica">Gossamer Links is now going to re-index your database, please be patient, this can take a while. Please note: this is only neccessary if you have manually changed the database outside of Gossamer Links.</font>
          </td>
      </tr>
    </table>
    </td></tr>
</table>
        ~;
        print qq~
<pre>Started at $t.

Indexing Links Database ... ~;
    }
    else {
        print "Started at $t.\n\nReindexing Gossamer Links Database ... ";
    }

# Get our Links db object.
    $links = $DB->table('Links');
    if ($links->{schema}->{search_driver} ne 'NONINDEXED') {
        $total = $links->count(VIEWABLE) || 0;
        $weights = $links->weight || {};
        $found = 0;
        foreach (keys %$weights) {
            $weights->{$_} > 0 and ($found = 1);
        }
        if (! $found) {
            if ($use_html) {
                print "<font color=red><b>No search weights have been defined, skipping!</b></font>\n";
            }
            else {
                print "No search weights have been defined, skipping!\n\n";
            }
        }
        else {
            print "$total links.\n";
            $links->reindex( { tick => 1000, max => 10000, cond => VIEWABLE } );
            print "\nDone!\n\n";
        }
    }
    else {
        if ($use_html) {
            print "<font color=red><b>Links table is using the NONINDEXED indexing scheme, skipping!</b></font>\n";
        }
        else {
            print "Links table is using the NONINDEXED indexing scheme, skipping!\n\n";
        }
    }

    print "Reindexing Category Database ... ";
    $category = $DB->table('Category');
    if ($category->{schema}->{search_driver} ne 'NONINDEXED') {
        $total = $category->count  || 0;
        $weights = $category->weight || {};
        $found = 0;
        foreach (keys %$weights) {
            $weights->{$_} > 0 and ($found = 1);
        }
        if (! $found) {
            if ($use_html) {
                print "<font color=red><b>No search weights have been defined, skipping!</b></font>\n";
            }
            else {
                print "No search weights have been defined, skipping!\n\n";
            }
        }
        else {
            print "$total categories.\n";
            $category->reindex( { tick => 1000, max => 10000 } );

            print "\nDone!\n\n";
        }
    }
    else {
        if ($use_html) {
            print "<font color=red><b>Category table is using the NONINDEXED indexing scheme, skipping!</b></font>\n";
        }
        else {
            print "Category table is using the NONINDEXED indexing scheme, skipping!\n\n";
        }
    }

# All done.
    $f = time();
    $e = $f - $s;
    printf ("All Done (%.2f s)\n\n", $e);
    if ($use_html) {
        print "</pre></body></html>";
    }
}

sub change_driver {
# -------------------------------------------------------------------
    my $new_driver  = shift or die "Please supply a drivername to change to";

    my $err = '';
    my $eLinks = $DB->editor('Links');
    my $eCats  = $DB->editor('Category');

    print "Please be warned that this action may take an extended period of time to complete\n\n";
    print "Updating Links Table search driver...\n";
    print " "x5, $eLinks->change_search_driver( $new_driver ) ? "Completed\n" : ( $err = "Error: $GT::SQL::error\n" );

    print "\nUpdating Category Table search driver...\n";
    print " "x5, $eCats->change_search_driver( $new_driver ) ? "Completed\n" :  ( $err ="Error: $GT::SQL::error\n" );

    if ($err) {
        print "\nThere were problems switching drivers.\n\n";
    }
    else {
        print "\nThe drivers have now been switched. Please be sure to reindex the tables.\n\n";
    }
}

