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

$lhash = trim($_SERVER['argv'][1]);
$rhash = trim($_SERVER['argv'][2]);

$first = @file_get_contents('http://g.e-hentai.org/g/'.urlencode($lhash).'/'.urlencode($rhash).'/');
if ($first === false) {
	die("404\n");
}

$matches = array();

preg_match('/id="gn">([^<]+)</', $first, $matches);
$title = $matches[1];

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

echo "Manga: $title ($pages pages)\n";

// Get first link...

preg_match('~a href="(http://g\.e-hentai\.org/s/[^"]+)"~', $first, $matches);
$url = $matches[1];

$i = 0;

for(;;) {
	
	echo sprintf("[%3d] ", ++$i);
	
	$page = file_get_contents($url);
	
	$matches = array();
	
	preg_match('/<img id="img" src="([^"]+)"/', $page, $matches);
	$imgurl = $matches[1];
	
	preg_match('/id="next"[^>]+href="([^"]+)"/', $page, $matches);
	$nexturl = $matches[1];
	
	$output_name = dirname(__FILE__).'/'.safename($title).'_'.sprintf("%03d", $i);
	if (file_exists($output_name.'.jpg') || file_exists($output_name.'.png')) {
		echo "exists, skipping\n";
		
	} else {
		
		echo $imgurl;
		
		$img = file_get_contents($imgurl);
		file_put_contents(
			$output_name.'.'.substr($imgurl, strlen($imgurl)-3),
			$img
		);
		
		echo " done\n";
	}
		
	if ($nexturl == $url) {
		break; // reached the end
	} else {
		$url = $nexturl; // continue
	}
	
}

echo "All pages downloaded.\n";

function safename($sz) {
	$ret = '';
	for ($i = 0, $e = strlen($sz); $i != $e; ++$i) {
		if (ctype_alnum($sz[$i])) {
			$ret .= $sz[$i];
		} else {
			$ret .= '_';
		}
	}
	return $ret;
}