#!/usr/bin/perl
# 文字コードUTF-8で保存してください。
# 漫画インデックス作成スクリプト
#   実行するとカレントディレクトリ・サブディレクトリ以下のファイルを走査し、
#   各ディレクトリのzip、pdfのインデックスページ(index.html)を作成します。

use strict;
use warnings;
use utf8;

use IO::File ();
use IO::Dir ();
use File::Spec ();
use File::Find ();
use Encode ();
use URI::Escape ();
use Cwd ();

sub html_escape($);
sub url_escape($);
sub create_index($$$);
sub gen_index($$$$$);

# 入出力やファイル名で使用する文字コードを指定してください。
my $enc = "CP932";


binmode(STDOUT, ":encoding($enc)");
binmode(STDERR, ":encoding($enc)");

create_index("漫画一覧", ".", $enc);

exit(0);

# 指定のディレクトリ以下を走査し、
# サブディレクトリに対しては再帰呼び出しを行いつつ、
# ディレクトリ内のファイル(zip, pdfのみ)、サブディレクトリのindex.htmlを作成します。
sub create_index($$$){
	my $title = shift();
	my $dir = shift();
	my $enc = shift();
	
	STDERR->printf("%s:%s\n", $title, Encode::decode($enc, $dir));
	
	my @subdirs = ();
	my @files = ();
	my $dh = IO::Dir->new($dir);
	while(my $entry = $dh->read()){
		if($entry =~ /^\./o){
			next;
		}
		
		my $path = File::Spec->catdir($dir, $entry);
		
		if(-d $path){
			push(@subdirs, $entry);
			next;
		}
		#STDERR->printf("\t%s\n", Encode::decode($enc, $path));
		next if ($path !~ /\.(?:zip|pdf)$/io);
		push(@files, $entry);
	}
	
	my $indexfile = File::Spec->catfile($dir, "index.html");
	gen_index($title, $indexfile, $enc, \@subdirs, \@files);
	
	
	foreach my $subdir(@subdirs){
		my $subtitle = Encode::decode($enc, $subdir);
		create_index($subtitle, File::Spec->catfile($dir, $subdir), $enc);
	}
	
	return;
}

# 与えられたファイル一覧、サブディレクトリ一覧の情報から
# インデックスページ(index.html)を生成します。
sub gen_index($$$$$){
	my $title = shift();
	my $path = shift();
	my $enc = shift();
	my $dirList = shift();
	my $fileList = shift();
	
	my $fh = IO::File->new(">$path");
	binmode($fh, ":encoding(UTF-8)");
	
	$fh->print(<<HEADER);
<html lang="ja">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<title>$title</title>
</head>
<body>
<ul>
HEADER
	
	map{
		my $path = $_;
		my $name = $path;
		
		$fh->printf(
			qq(<li><a href="%s/">%s</a></li>\n),
			html_escape(join("/", map{url_escape($_)}split(/\//o, $path))),
			html_escape($name),
		);
	}sort(map{
		Encode::decode($enc, $_);
	}@$dirList);
	
	map{
		my $path = $_;
		my $name;
		$path =~ /([^\/]*)\.(?:zip|pdf)$/o;
		$name = $1;
		
		$fh->printf(
			qq(<li><a href="%s">%s</a></li>\n),
			html_escape(join("/", map{url_escape($_)}split(/\//o, $path))),
			html_escape($name),
		);
	}sort(map{
		Encode::decode($enc, $_);
	}@$fileList);
	
	$fh->print(<<FOOTER);
</ul>
</body>
</html>
FOOTER
	
	$fh->close();
}

# HTMLエスケープを行います。
sub html_escape($){
	my $str = shift();
	$str =~ s/&/&amp;/go;
	$str =~ s/"/&quot;/go;	#"
	$str =~ s/>/&gt;/go;
	$str =~ s/</&lt;/go;
	return $str;
}

# URLエスケープを行います。
sub url_escape($){
	my $str = shift();
	#$str =~ s/%/%25/go;
	#$str =~ s/ /%20/go;
	return URI::Escape::uri_escape_utf8($str);
}