#!/usr/bin/perl -w

# 00Index -> SQL

use strict;

if ($#ARGV < 0) {
  print "./00_ftp.pl /pub/CircleMUD/contrib/code Code /home/ftp/pub/CircleMUD/contrib/code/00Index\n";
  exit;
}

use CM;

my $g = new CM;
my $dbh = $g->dbi();
my $path = shift;
die "bad path" if (! -d "/home/ftp$path");
my $category = shift;

my %files;
my $now = time;
my $name;
my $text;

while (<>) {
  next if (/^\s*$/);

  if (not /^\s/) {
    $files{$name} = $text if (defined $name);
    $text = '';
    $name = '';
    /^(\S+)\s+(.*)/;
    $name = $1;
    $text = $2;
  } elsif (/^\s+(.*)/) {
    $text .= ' ';
    $text .= $1;
  }
}
$files{$name} = $text;

my $file;
foreach $file (sort keys %files) {
  next if ($file =~ /README|00Index/);
  next if (! -f "/home/ftp$path/$file");

  my $text = $files{$file};
  my $textfile = '';
  my $readme = $file;
  while ((not $textfile) && ($readme =~ /\./)) {
    $readme =~ s/\..*//;
    $textfile = "http://ftp.circlemud.org$path/$readme.README" if (exists $files{"$readme.README"});
  }

  my $days = int(-M "/home/ftp$path/$file");
  my $time = `date +'%Y-%m-%d %T' -d '$days days ago'`;
  chomp($time);
  $dbh->do('INSERT INTO entries (id,name,filename,download_size,documentation,short_description,category,updated,created) ' .
			'VALUES(NULL,?,?,?,?,?,?,?,?)', undef,
			$file, $file, -s "/home/ftp$path/$file", $textfile,
			$text, $category, $time, $time);
  print "$file: [$textfile]\n";
}
$dbh->disconnect();
