#!@PHP-BIN@
<?php
/**
 * PHP Fortune 
 *
 * A command-line script for pulling a random fortune from a fortune file.
 * /usr/share/fortune or /usr/share/games/fortunes are assumed as
 * the base directory. If no filename is provided, a random fortune from a
 * fortune file in the base directory will be pulled. If a valid fortune file
 * is provided, an optional index may also be used to pull a specific fortune
 * from the file.
 *
 * Usage:
 * <code>
 * // pull a random fortune from the fortunes fortune file
 * $ phpFortune fortunes
 *
 * // pull fortune 3 from the fortunes fortune file
 * $ phpFortune 3 fortunes
 *
 * // pull a random fortune from any fortune file in the base directory
 * $ phpFortune
 * </code>
 *
 * @author    Matthew Weier O'Phinney <mweierophinney@gmail.com>
 * @copyright 2005 - 2007, Matthew Weier O'Phinney
 * @version   @package_version@
 */
require_once 'File/Fortune.php';

if (is_dir('/usr/share/fortune')) {
    $base = '/usr/share/fortune';
} elseif (is_dir('/usr/share/games/fortunes')) {
    $base = '/usr/share/games/fortunes';
} else {
    echo "Cannot find base fortunes directory.\nNeither /usr/share/fortune nor /usr/share/games/fortunes exist\n";
    exit(1);
}

$file  = null;
$index = null;
if ($argc > 1) {
    $args = $argv;
    array_shift($args);
    $tmp = array_shift($args);
    if (is_numeric($tmp)) {
        $index = $tmp;
        if (count($args)) {
            $file = array_shift($args);
        }
    } else {
        $file = $tmp;
    }
}

if ((null !== $file) && ('/' != substr($file, 0, 1))) {
    $file = $base . '/' . $file;
}
if ((null !== $file) && !file_exists($file)) {
    echo "Invalid fortune file specified\n";
    exit(1);
}
if (null === $file) {
    $index = null;
    $file = $base;
}

try {
    $fortunes = new File_Fortune($file);
    if (null === $index) {
        echo $fortunes->getRandom();
    } else {
        $index = (int) $index;
        if (!isset($fortunes[$index])) {
            echo "Fortune '$index' does not exist in this fortune file";
        } else {
            echo $fortunes[$index];
        }
    }
} catch (File_Fortune_Exception $e) {
    echo "Unable to retrieve fortune\n";
}
