#!/usr/bin/perl

use Jcode;

$datdir=$ARGV[0]; #朔の cache ディレクトリの位置 ex) ~/saku-0.4.0/cache
$str=$ARGV[1]; #スレッドのタイトル ex) "ネタ板"
$baseurl="http://debian-99:8000"; #末尾に / をつけないでください。

$str = Jcode->new($str)->h2z->utf8;
$filename = unpack("H*", $str);
$datfile = "$datdir/thread_\U$filename\E/body.cache";

$num=0;

open(IN, "$datfile") or die;
@list = <IN>;
close(IN);

foreach(@list){
	$dat = @list[$num];
	@thread = split(/<>/, $dat);
	foreach(@thread){
		if ($_ =~ /body:/){ $body = $_; $body =~ s/body://; chomp $body;}
		if ($_ =~ /name:/){ $name = $_; $name =~ s/name://; chomp $name;}
		if ($_ =~ /mail:/){ $mail = $_; $mail =~ s/mail://; chomp $mail;}
		if ($_ =~ /message:/){ $message = $_; $message =~ s/message://; chomp $message;}
		if ($_ =~ /attach:/){ $attach = $_; $attach =~ s/attach://; chomp $attach;}
		if ($_ =~ /suffix:/){ $suffix = $_; $suffix =~ s/suffix://; chomp $suffix;}
	}

	($sec, $min, $hour, $mday, $mon, $year) = localtime(@thread[0]);
	$year = $year + 1900;
	$date = sprintf("%d/%02d/%02d %02d:%02d:%02d", $year, $mon, $mday, $hour, $min, $sec); 
	$id = substr(@thread[1], 0, 8);

	#if ($num == 0) { $title = "<>$ARGV[1]"; }
	if ($num == 0) { $title = "$ARGV[1]"; }
	if ($name eq "") { $name = "名無しさん"; }
	$gt{$id} = $num + 1;

	#if ($attach ne "") { $attachurl = getAttach($attach); }
	if ($attach ne "") {
		$attachurl = "$baseurl/thread.cgi/thread_\U$filename\E/@thread[1]/@thread[0].$suffix";
		$body = join("<br>", $body, "[$suffix]", $attachurl);
        }

	if($body =~ /&gt;&gt;(........)/){
		if($gt{$1} ne ""){ $body =~ s/&gt;&gt;(........)/&gt;&gt;$gt{$1}/g; }
	}
	if ($body eq ""){ $body = join("<br>", "[削除]", $message); }
	
	#print $name, "<>", $mail, "<>", $date, " id:", $id, "<>", $body, $title, "\n";
	print $name, "<>", $mail, "<>", $date, " id:", $id, "<>", $body, "<>", $title, "\n";

	$num = $num +1;
	$body = ""; $name = ""; $mail = ""; $title = ""; $attach = ""; $suffix = ""; $attachurl = "";
}

