<?php
if (count($_SERVER['argv']) != 2) {
	die('Usage: manga.php description');
}

$desc = trim($_SERVER['argv'][1]);

$first = file_get_contents('http://www.mangainn.com/manga/chapter/'.urlencode($desc));

$matches = array();
preg_match('/\<b style="color:white"\>(\d+)\<\/b\>/', $first, $matches);
$pages = $matches[1];

echo '#'.ucwords(str_replace('_', ' ', $desc))." ($pages pages)\n";

for ($i = 1; $i < ($pages+1); $i++) {
	
	echo sprintf("[%3d] ", $i);
	
	$page = file_get_contents('http://www.mangainn.com/manga/chapter/'.urlencode($desc).'/page_'.$i);
	
	$matches = array();
	preg_match('/<img[^>]*src="(http:\/\/static.mangainn.com\/mangas\/[^"]+)"/', $page, $matches);
	
	$url = $matches[1];
	
	echo $url;
	
	$img = file_get_contents($url);
	file_put_contents(
		dirname(__FILE__).'/'.$desc.'-'.sprintf("%03d", $i).'.'.substr($url, strlen($url)-3),
		$img
	);
	
	echo " done\n";	
}

echo "All pages downloaded.\n";
