#!/bin/perl

require "config";

use lib '../..';
use CGI;

$query = new CGI;

if (!($qstring = $query->param('keywords'))) {
    &list_threads;
}

else {
    
    ($threadnum, $confirm) = split(/,/,$qstring,2);
	 
    if ($confirm eq 'y') {
	&delete_thread;
    }
    
    elsif ($confirm eq 'n') {
	print "Location: $base_url/ADMIN/removethread.cgi\n\n";
    }
    
    else {
	&ask_for_confirmation;
    }
    
}

###
sub list_threads {
    
    open(LOCK,"../list.lock");  flock(LOCK,2);

    open(THREADFILE,"$main_thread_file") || die;

    print "Cache-Control: no-cache\nPragma: no-cache\nContent-type: text/html\n\n<HTML><HEAD><TITLE>Remove a Thread</TITLE></HEAD><BODY BGCOLOR=\"#FEFEFE\"><A HREF=\"admin.cgi\">Back to Administration</A><H1>Remove a Thread</H1>Click on the thread you wish to remove:<HR>";

# get, print threads
    while(<THREADFILE>) {
	chop;
	($num,$title,$author,$email,$date_mod,$replies,$last_mod,
	 $mod_val,$mod_num) = split(/\t/);
	
	if (!$mod_val) {
	    $date = &date_format($date_mod);
	    $last = &date_format($last_mod);
	    
	    print "<STRONG>$num</STRONG> $date <A HREF=\"removethread.cgi?$num\">$title</A> - $author [ $replies - <EM>$last</EM> ]<BR>\n";
	}
    }
    
    print "</BODY></HTML>";

    flock(LOCK,8);
    close(THREADFILE);

}

###
sub delete_thread {
    open(LOCK,"../list.lock"); flock(LOCK,2);

    open(THREADFILE,"$main_thread_file") || die;

    open(BAKFILE,">$main_thread_file.bak") || die;
	
    while(<THREADFILE>) {
	if (!(/^$threadnum\t/o)) {
	    print BAKFILE;
	}
    }
    
    open(THREADFILE,">$main_thread_file") || die;
    open(BAKFILE,"$main_thread_file.bak") || die;
    
    while(<BAKFILE>) {
	print THREADFILE;
    }
    
    unlink "../DATA/$threadnum.th";
    
    flock(LOCK,8);
    close(THREADFILE);
    
    print "Location: $base_url/ADMIN/removethread.cgi\n\n";
}

###
sub ask_for_confirmation {
    open(LOCK,"../list.lock"); flock(LOCK,2);
    
    open(THREADFILE,"$main_thread_file") || die;
    
    while(<THREADFILE>) {
	if (/^$threadnum\t/o) {
	    chop;
	    ($num,$title,$author,$email,$date_mod,$replies,$last_mod,
	     $mod_val,$mod_num) = split(/\t/);
	    
	    $date = &date_format($date_mod);
	    $last = &date_format($last_mod);
	    last;
	}
    }
    
    print "Content-type: text/html\n\n";
    
    print <<EOF
<HTML>
<HEAD><TITLE>Remove a Thread - Confirmation</TITLE></HEAD>
<BODY BGCOLOR="#FEFEFE">
<H3>Are you sure you want to remove this thread?</H3>
<TABLE>
<TR><TD><STRONG>Title:</STRONG> </TD><TD>$title<BR></TD></TR>
<TR><TD><STRONG>Name:</STRONG> </TD><TD>$author $email<BR></TD></TR>
<TR><TD><STRONG>Date Started:</STRONG> </TD><TD>$date<BR></TD></TR>
<TR><TD><STRONG>Date Last Changed:</STRONG> </TD><TD>$last<BR></TD></TR>
<TR><TD><STRONG>Replies:</STRONG> </TD><TD>$replies<BR></TD></TR>
</TABLE>
<P>
<A HREF="removethread.cgi?$threadnum,y">Yes</A><P>
<A HREF="removethread.cgi?$threadnum,n">No</A>
</BODY></HTML>
EOF
}











