#!/usr/bin/perl

# リダイレクト先
$url = "http://www.it-kikaku.jp/topics/";
#$url = "http://192.168.11.73/topics/";

# 現在のディレクトリをオープンする
opendir(DIR, ".") || &errorPage("ディレクトリを開けません。");

# 配列に読み込む
@files = readdir(DIR);

# ディレクトリをクローズする
closedir(DIR);

# ページの最大値をチェック
$max = 0;
$fnameMax = "";
$indexFlg = false;
foreach(@files) {
	$fname = $_;
	if($fname =~/\.LCK/){
		# ロックファイルなので処理なし
	} else {
		if($fname =~ /topics/) {
			$temp = $';
			if($temp =~ /\./) {
				$temp = $`;
			}
			if($temp > $max) {
				$max = $temp * 1;
				$fnameMax = $fname;
			}
		#} elsif($_ eq "index.htm") {
		#	$indexFlg = true;
		}
	}
}
# 最大値が空の場合、index.htmとする
if($max = 0) {
	$fnameMax = "index.htm";
}

# リダイレクト処理
if($fnameMax eq "index.htm") {
	if($indexFlg) {
		print "Location: $url$fnameMax\n\n";
	} else {
		# index.htmが無いのでエラーを表示
		&errorPage("index.htmがありません。");
	}
} else {
	print "Location: $url$fnameMax\n\n";
}

exit;

#######################################################
# エラー
#######################################################
sub errorPage {
	($err) = @_;
	
	my %html_contents = (
		ERR => $err
	);

	open(FIN, "err.htm") || die "err.htm をオープンできません：$!\n";
	local($/) = undef;
	$template = <FIN>;
	close(FIN);
	
	$template =~ s/\$([A-Z]+)/;
	my $value = $html_contents{$1};
	jcode::convert(\$value, "sjis");
	$value;
	/ge;
	
	print "Content-type:text/html\n\n";
	print $template;
	
	exit;
}
