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

$series = trim($_SERVER['argv'][1]);
$chapter = trim($_SERVER['argv'][2]);

$first = file_get_contents('http://www.mangabird.com/'.$series.'-'.$chapter);

$matches = array();
preg_match_all('/pageslink"\>(\d+)\</', $first, $matches);
$pages = intval(end($matches[1])) + 1;

echo ucwords($series)." Ch. $chapter ($pages pages)\n";

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

echo "All pages downloaded.\n";