#!/usr/bin/perl -w
#
# mnogosearch-configure: Program to (re)configure mnogosearch
# (C)2000,2001 Craig Small <csmall@debian.org>
# (C)2004 by Philipp Hug <debian@hug.cx>

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
$INDEXER_CONF='/etc/mnogosearch/indexer.conf';
$SEARCH_HTM='/etc/mnogosearch/search.htm';

#use Debian::DebConf::Client::ConfModule ':all';
#my $version=version 2;

sub load_config_files()
{
    $main::indexerconf = `cat $INDEXER_CONF 2>/dev/null`;
    $main::searchhtm = `cat $SEARCH_HTM 2>/dev/null`;
}

sub get_debconf_values()
{
    $main::dbmode=get('mnogosearch-common/database_mode');
    $main::dbhost = get('mnogosearch-common/database_host');
    $main::dbport=  get('mnogosearch-common/database_port');
    $main::dbname= get('mnogosearch-common/database_name');
    $main::dbuser= get('mnogosearch-common/database_user');
    $main::localdb= get('mnogosearch-common/local_database');
}



sub update_file(@)
{
    if ($localdb eq 'true') {
      $dbserver = "";
    } else {
      $dbserver = "$dbhost";
      if ($dbport ne '') {
        $dbserver = "$dbserver:$dbport";
      }
    }

    if (! ($_[0] =~ s#\nDBAddr\s.*\n#\nDBAddr $dbtype://$dbuser:$dbpass\@$dbserver/$dbname/\?dbmode=$dbmode\n#)) {
      $_[0] = "DBAddr $dbtype:\/\/$dbuser:$dbpass\@$dbserver\/$dbname\/\?dbmode=$dbmode\n$_[0]";
    }

    if ($_[0] =~ /^[^#]/) 
    {
        $_[0] = "# start\n" . $_[0];
    }
}

sub save_config_files()
{
  #system ("savelog -c 100 $INDEXER_CONF")
  #          && die ("couldn't rotate $INDEXER_CONF");
  open (CONF, ">$INDEXER_CONF") || die ("couldn't open $INDEXER_CONF");
  print CONF $main::indexerconf;
  close (CONF);

  #system ("savelog -c 100 $SEARCH_HTM")
  #          && die ("couldn't rotate $SEARCH_HTM");
  open (CONF, ">$SEARCH_HTM") || die ("couldn't open $SEARCH_HTM");
  print CONF $main::searchhtm;
  close (CONF);
}

 ($dbmode, $dbhost, $dbport, $dbname, $dbuser, $dbpass, $localdb, $dbtype) = @ARGV;
if ($dbtype eq '') {
  die "Usage:\nmnogosearchconfig <dbmode> <dbhost> <dbport> <dbname> <dbuser> <dbpass> <localdb> <dbtype>\n";
}

load_config_files();
#get_debconf_values();

update_file($indexerconf);
update_file($searchhtm);
save_config_files();
