#!/usr/local/bin/php -q
<?
/* 
 * hjgork:  Joins files split with hjsplit
 * Written by Steve Grecni  gid[AT]gifpaste.net
 *
 * I called it hjgork, because hjsplit is brain dead, it's just simple
 * concatination, no CRC checking, no nothing, there's no way to tell if you
 * downloaded the file and joined it completely or not.  So this script
 * ain't making any guarantees.
 */

function hjgork($file) {
	$f = substr($file, 0, -4);
	if(is_file($f)) {
		echo "$f already exists, skipping...\n";
	} else {
		echo "Combining $f...\n";

		$cmd = 'cat >'. escapeshellarg($f);
		for($i = 1; is_file(sprintf("$f.%03d", $i)); $i++) {
			$cmd .= ' '. escapeshellarg(sprintf("$f.%03d", $i));
		}
		exec("$cmd");
	}

	echo "Delete unjoined files? [y/N] ";
	$c = fgets(STDIN);

	if(strtolower(trim($c)) == 'y') {
		for($i = 1; is_file(sprintf("$f.%03d", $i)); $i++) {
			unlink(sprintf("$f.%03d", $i));
		}
	}
	echo "\n\n";
}

function help() {
	echo "Usage: ". basename($_SERVER['argv'][0]) ." [directory]\n\n";
	exit();
}

if($_SERVER['argv'][1]) {
	$dir = $_SERVER['argv'][1];
} else {
	$dir = $_SERVER['PWD'];
}
if(!@chdir($dir)) {
	echo "Failed to change directory to $dir.\n\n";
	help();
}

/* open up the current directory */
$dh = opendir('.');
$numfiles = 0;
while($f = readdir($dh)) {
	/* only look at files endin in .001 */
	if(substr($f, -4) == '.001' && is_file($f)) {
		$numfiles++;
		hjgork($f);
	}
}

if($numfiles) {
	if($numfiles > 1) $plur = 's';
	echo "Successfully joined $numfiles file$plur\n";
} else {
	echo "No hjsplit files found in $dir\n\n";
	help();
}

?>
