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

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

$first = @file_get_contents('http://www.mangafox.me/manga/'.urlencode(str_replace(' ', '_', $series)).'/v'.sprintf("%02d", $volume).'/c'.sprintf("%03d", $chapter).'/1.html');
if ($first === false) {
	die("404\n");
}

$matches = array();
preg_match('/of (\d+)/', $first, $matches);
$pages = intval($matches[1]);

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

for ($i = 1; $i < ($pages + 1); $i++) {
	
	echo sprintf("[%3d] ", $i);
	
	$output_name = dirname(__FILE__).'/'.$series.'-'.sprintf("%03d-%03d", $chapter, $i);
	if (file_exists($output_name.'.jpg') || file_exists($output_name.'.png')) {
		echo "exists, skipping\n";
		continue;
	}	
	
	$page = file_get_contents('http://www.mangafox.me/manga/'.urlencode(str_replace(' ', '_', $series)).'/v'.sprintf("%02d", $volume).'/c'.sprintf("%03d", $chapter).'/'.$i.'.html');
	
	$matches = array();
	preg_match('/<img[^>]*src="([^"]+)"/', $page, $matches);
	
	$url = $matches[1];
	
	echo $url;
	
	$img = file_get_contents($url);
	file_put_contents(
		$output_name.'.'.substr($url, strlen($url)-3),
		$img
	);
	
	echo " done\n";
	
}

echo "All pages downloaded.\n";