#!/usr/bin/perl
use DB_File;
use Fcntl;
use CGI qw(:standard);

my $dbm_file = "./artist_index.db";
my %hash;
local *DBM;

my $db = tie %hash, "DB_File", $dbm_file, O_CREAT | O_RDWR, 0644 or
die "Could not tie to $dbm_file: $!";
my $fd = $db->fd;
open DBM, "+<&=$fd" or die "Could not dup DBM for lock: $!";
flock DBM, 2;
undef $db;

print header,"<html><body style='font-family:\"Georgia\",Times,serif;font-size:12px;margin:10px 0px 0px 0px;padding:0px'>\n";

if(@artists = param()) {
  foreach $artist (@artists) {
    $posts = $hash{$artist};
    $post  = param($artist);
    $post  =~ s/[^\w\s\-\/.i+&]//g;
    $date  = (split('_', $post))[0];
    $link  = substr($post, index($post, "_")+1);
    
    if($posts) {
      if($posts =~ m|$link|) {
        if($date eq "deletepost") {
          $posts =~ s/(, <a target="_parent" href=$link>(.*?)<\/a>)|( <a target="_parent" href=$link>(.*?)<\/a>,)//;
          print "deleting post: ".$link;
          $hash{$artist} = $posts;
        } elsif($date eq "deleteartist") {
          delete($hash{$artist});
          print "deleting artist: ".$artist;
        } else {
          $posts =~ s/<a target="_parent" href=$link>(.*?)<\/a>/<a target="_parent" href=$link>$date<\/a>/;
          print "updating post: "."<a target=\"_parent\" href=$link>$date<\/a>";
          $hash{$artist} = $posts;
        }
      } elsif ($date ne "deletepost" and $date ne "deleteartist") {
        $posts = " <a target=\"_parent\" href=$link>$date</a>,$posts";
        print "new post: "."<a target=\"_parent\" href=$link>$date</a>";
        $hash{$artist} = $posts;
      } elsif($date eq "deleteartist") {
        delete($hash{$artist});
        print "deleting artist: ".$artist;
      }
    } elsif ($date ne "deletepost" and $date ne "deleteartist") {
      $hash{$artist} = " <a target=\"_parent\" href=$link>$date</a>";
      print "new artist: ".$artist;
    }
  }
} else {
  @artists = sort keys %hash;
  $i = 0;

  foreach $artist (@artists) {
    $posts = $hash{$artist};

    if($i % 25 == 0) {
      print "<a target=\"_parent\" href=\"/archives/archive.html\">CLICK FOR ARCHIVES</a><br>$artist $posts<br>\n";
    } else {
      print "$artist $posts<br>\n";
    }
    $i++;
  }
}
print "<body></html>";

untie %hash;
