<?php

// Rollup

$version = file_get_contents(__DIR__."/version.txt");

// Includes

require (__DIR__."/functions.php");

// Load preferences

$prefs_file = "/Users/".get_current_user()."/Library/Preferences/org.profiteroles.Rollup.php";
if (!file_exists($prefs_file)) {
	if (!copy(__DIR__."/prefs.php",$prefs_file)) {
		echo "Error creating preferences file";
		die;
		}
	}
$p = unserialize(file_get_contents($prefs_file));

$p['etbin'] = __DIR__."/exiftool";
$p['pfiletypes'] = array("jpg","jpeg","dng","heic","png","gif");
$p['vfiletypes'] = array("mov","mp4","m4v");
$p['screenshot_dims'] = array(320,640,750,828,1125,1242);
$p['delimiters'] = array(" ","_","-","+");

// Debug options

$p['debug_verify_names'] = 0; // Verify newnames against those made with a prior version of rollup
$p['debug_lens'] = 0;  // Output raw lens data to verify formatting

// No files dragged

array_shift($argv);

switch (@$argv[0]) {
	case "Preferences...":
		if (!exec("php ".__DIR__."/RollupPrefs.php")) {
			echo "\nALERT:Warning|Google did not accept your API key\n";
			}
		die;
	case "Check for Updates...":
		$curr_version = @file_get_contents("https://www.profiteroles.org/git/profiteroles/Rollup/raw/master/version.txt");
		if (!$curr_version) {
			echo "\nALERT:Can't connect|Error checking for latest version\n";
			die;
			}
		if ($curr_version > $version) {
			if(askMulti("Rollup ".$curr_version." is available (you have ".$version.")", array("Cancel","Download")) == 1) {
				exec("open https://www.profiteroles.org/git/profiteroles/Rollup");
				echo "QUITAPP\n";
				} else {
				die;
				}
			} else {
			echo "\nALERT:Up-to-date|".$version." is the latest version.\n";
			die;
			}
	}

// API key check

if (!@$p['key'] && (strpos($p['pt'],"%PLACE") != false || strpos($p['vt'],"%PLACE"))) {
	echo "Warning: \"%PLACE\" will not work without an API key!\n";
	}

// Build list of valid dropped files

foreach ($argv as $target) {

	if (is_dir($target)) {
		$it = new RecursiveDirectoryIterator($target);
		foreach(new RecursiveIteratorIterator($it) as $file) {
    		if (in_array(strtolower(pathinfo($file,PATHINFO_EXTENSION)), $p['allowed'])) {
				$files[] = $file->getpathname();
				}
			}	
		} elseif (in_array(strtolower(pathinfo($target,PATHINFO_EXTENSION)), $p['allowed'])) {
			$files[] = $target;	
		}
		
	}
	
if (!@$files) { echo "\nALERT:No supported files|Supported filetypes: ".implode(", ",$p['allowed'])."\n"; die; } else { sort($files); }
if (count($files) > $p['limit']) { if (!ask("Really process ".count($files)." files?")) { die; } }

// Process files

$i = 0;

foreach ($files as $file) {

	unset($parts, $ext, $mparts, $z, $e);

	$parts = pathinfo($file);
	$ext = strtolower($parts['extension']);

	$z['%FILE'] = $parts['filename'];
	$z['%EXT'] = $parts['extension'];
	
	if ($p['debug_verify_names']) {
		$p['maxlength'] = 999;
		$z['%FILE'] = substr($parts['filename'],-8,8);
		echo "[VERIFY]";
		} else {
		echo $parts['basename'];
		}
	
	if (strlen($parts['basename']) > $p['maxlength']) {
	
		echo "-> SKIP\n";
		
		} else {

		$raw = eval("return ".shell_exec($p['etbin']." -php ".escapeshellarg($file)));
		if (is_array($raw[0])) { $e = $raw[0]; } else { echo "Exiftool error\n"; die; }

		$z['%DTO'] = formatDateTime($e);
		$z['%DUR'] = formatDuration($e);
		$z['%SW'] = formatSoftware($e,$p);
		$z['%MODEL'] = formatModel($e);
		$z['%LENS'] = formatLens($e);
		$z['%PLACE'] = formatPlace($e,$p);
	
		if (in_array($ext,$p['pfiletypes'])) {
			$newname = str_replace(array_keys($z),array_values($z),$p['pt']);
			} elseif (in_array($ext,$p['vfiletypes'])) {
			$newname = str_replace(array_keys($z),array_values($z),$p['vt']);
			}
		
		// Prevent repeat delimiters from null keys 
		// The following is a fairly lame hack
		
		foreach ($p['delimiters'] as $char) {
			$d_a[] = $char;
			$d_a[] = $char.$char;
			$d_a[] = $char.$char.$char;
			$d_b[] = $char;
			$d_b[] = $char;
			$d_b[] = $char;
			}
	
		$newname = str_replace($d_a,$d_b,$newname);
		
		if (!@$newname) {
			echo " -> ERROR\n";
			} else {
			echo " -> ".$newname."\n";
			if ($p['debug_verify_names']) {
				if ($parts['basename'] != $newname) {
					echo "FAIL";
					echo "\nALERT:Filename changed|".$parts['basename']." VS ".$newname;;
					} else {
					echo "pass";
					}
				} else {
				if (!@$p['dry_run']) {
					rename($file,$parts['dirname']."/".$newname);
					} else {
					echo "\nDisable dry run to rename files!";
					}
				}
			}
		
		if ($p['debug_lens']) { echo "\n".@$e['LensModel']."\n".@$e['FocalLength']."\n"; }
		
		echo updateProgress($i,count($files));
		$i++;

		}
	}

?>
