#!/usr/bin/php
<?php

	// Setup some constants
	define(EDITOR, '/usr/bin/vim + +:start');
	define(TEMPFILE, '/tmp/snap.txt');
	define(BACKUP, '.cbk');

	// Verify that there is only one argument
	if ($argc != 2) {
		showSyntax();
		exit;
	}
	
	// Verify that it's a file
	if (!is_file($argv[1])) {
		echo "Error, not a valid file.\n";
		exit;
	}
	
	// Create the backup directory if it doesn't already exist
	if (!is_dir(BACKUP)) {
		mkdir(BACKUP);
	}
	
	// Figure out the next number
	for ($i=1; $i<=999; $i++) {
	
		// Add zero's to the revision number
		if ($i < 10) {
			$rev = "000$i";		
		} elseif ($i < 100) {
			$rev = "00$i";
		} elseif ($i < 1000) {
			$rev = "0$i";
		} else {
			$rev = $i;
		}

		// Setup the revision and snap filenames
		$revFile = BACKUP . '/' . $argv[1] . '__' . $rev;
		$snapFile = BACKUP . '/' . $argv[1] . '__snap';
		
		// If the file doesn't exist
		if (!file_exists($revFile)) {
		
			// Create the backup
			copy ($argv[1], $revFile);
			
			// We're done here, bail from the loop
			break;

		}

	}
	
	// Create the temp file
	$tempData  = "===== ( $rev ) ===== [ " . date('m/d/Y h:i:s a') . " ] =====\n\n\n";
	file_put_contents(TEMPFILE, $tempData);

	// Launch the temp file in the editor
	passthru(EDITOR . ' ' . TEMPFILE);
	
	// Grab the contents of the previous snap file
	if (file_exists($snapFile)) {
		$snapBefore = file_get_contents($snapFile);
	}
	
	// Grab the contents of the updated temp file
	$snapTemp = file_get_contents(TEMPFILE);
	
	// Setup the new snap file
	if ($snapBefore) {
		$snapAfter = $snapBefore . $snapTemp . "\n\n";
	} else {
		$snapAfter = $snapTemp . "\n\n";
	}
	
	// Write the new snap file
	file_put_contents($snapFile, $snapAfter);
	
	// Kill the temp file
	unlink(TEMPFILE);
	
	/*****
	 * showSyntax
	 */
	function showSyntax() {
	
		echo "Snap v0.1\n";
		echo "\n";	
		echo "SYNTAX: snap <filename>\n";
	
	}

?>
