#!/usr/bin/perl
use strict;
use warnings;
use CGI;
use lib '/home/dsktnk/local/lib/perl5';
use Text::Markdown::Discount qw/markdown/;
#use Text::Markdown qw/markdown/;
use LWP::UserAgent;
use URI;
use YAML::XS;

my $obj = new CGI;
my $url = $obj->param('url');

my $ua = LWP::UserAgent->new;
$ua->agent('Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');

my $request = HTTP::Request->new('GET' , "$url");
my $response = $ua->request($request);
my $data = $response->content;


my ($frontmatter,$md,$i);
# YAML frontmatter
#if ($data =~/(^-{3}${1}.*?-{3}${1})/s){
if ($data =~/^-{3}${1}(.*?)-{3}${1}/s){
    $frontmatter = "$1";
}
my $yf = YAML::XS::Load($frontmatter);
my $titletag=$yf->{title};
print qq|Content-type: text/html\n\n|;
print &header_html($titletag);
print &adsense;
print qq|<h1 class="title"><a href="http://dsktnk.sakura.ne.jp/memo/">memo</a></h1>|;


# パンくずリスト
my $uri   = URI->new($url);
my $relative;
if ($uri){
  my @line = split ( /\// , $uri->path );
  @line = grep $_ !~ /^\s*$/, @line;
  shift @line;
  pop @line;
if (@line){
  for my $i (@line){
    $relative .= "$i/";
    print qq|<b class="dir"><a href="index.cgi?d=$relative">$i</a></b>|;
  }
  print qq|<hr />|;
}
}



# Markdown
my @line = split ( /\n/ , $data );
my ($ln,$line);
my $i=0;
my $item ="-{3}";

foreach $ln(@line){
    if ($ln =~ /$item/){
        $i++
    }
    elsif ($i>1){
        $line .= "$ln\n";
    }
}
#my $m = Text::Markdown::Discount->new;
my $html = markdown($line);

#my $html = markdown($line);

print $html;
print "<hr />";
print $frontmatter;
print &footer_html;

sub header_html{
my $title=$_[0];
my $printlines = <<"__EOF__";
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
	"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja">
<head>
        <title>$title</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta http-equiv="Content-Style-Type" content="text/css" />
	<meta name="author" content="dsk" />
	<link rel="stylesheet" href="index.css" type="text/css" />
</head>
<body>
__EOF__
return $printlines;
}

sub footer_html{
my $printlines = <<"__EOF__";
</body>
</html>
__EOF__
return $printlines;
}

sub adsense{
my $printlines = <<"__EOF__";
<html><script type="text/javascript"><!--
google_ad_client = "ca-pub-8463396328485458";
/* Mediawiki TOP */
google_ad_slot = "3447929082";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></html>
__EOF__
return $printlines;
}