<?php

// --------------------------------------------
function is_windows() {
	return (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN');
}

// --------------------------------------------
function test_parameter($values, $target) {
	return in_array($target, $values);
}

// --------------------------------------------
function get_log_folder() {
	if (is_windows()) {
		return "Running with rifles";
	} else {
		return ".running_with_rifles";
	}
}

// --------------------------------------------
function get_log_filename() {
	return "metagame.log";
}

function verify_log_writability($path) {
	if (file_exists($path) || mkdir($path)) {
		// ok, verify it's writeable
		$f = fopen($path . "/" . get_log_filename(), "w");
		if (!$f) {
			// failed
			$path = "";
		} else {
			fclose($f);
		}
	} else {
		$path = "";
	}

	return $path != "";
}

// --------------------------------------------
function get_log_path() {
	$path = "";

	global $argv;
	if (!test_parameter($argv, "single_player")) {
		// servers use working directory - we can have several servers on one machine
		return $path;
	}

	if (is_windows()) {
		// windows:
		// 1) go for AppData/Roaming/Running with rifles/
		// works for Vista / 7 in medium integrity, and XP always(?)
		if ($path == "") {
			$path = getenv("appdata");
			if ($path != "") {
				$path .= "/" . get_log_folder();
				if (!verify_log_writability($path)) {
					$path = "";
				}
			}
		}
		
		// if it fails, we may be running in low integrity mode
		// 2) go for AppData/Local/Temp/Low
		// -- works for low integrity processes (Vista / 7 only) - preferred
		// -- another choice would be AppData/LocalLow, but as it happens, there's no environment variable for it
		if ($path == "") {
			$path = getenv("temp");
			if ($path != "") {
				$path .= "/Low/" . get_log_folder();
				if (!verify_log_writability($path)) {
					$path = "";
				}
			}	
		}

		// 3) try temp directly then
		// -- maybe XP doesn't have temp\Low?
		if ($path == "") {
			$path = getenv("temp");
			if ($path != "") {
				$path .= "/" . get_log_folder();
				if (!verify_log_writability($path)) {
					$path = "";
				}
			}
		}

		// path is now either 
		// .../AppData/Local/Temp/Low/Running with rifles
		// .../AppData/Local/Temp/Running with rifles
		// or the equivalent in Windows XP
		// "" (working directory -- using it fails without admin rights, but don't care)

	} else {
		// linux

		if ($path == "") {
			$path = getenv("HOME");
			if ($path != "") {
				$path .= "/" . get_log_folder();
				if (!verify_log_writability($path)) {
					$path = "";
				}
			}
		}
	}

	return $path;
}




?>