#!/usr/bin/env php
<?php

require(__DIR__ . '/../Parser.php');
require(__DIR__ . '/../Markdown.php');

$flavor = 'cebe\\markdown\\Markdown';
$flavors = [
	'gfm' => ['cebe\\markdown\\GithubMarkdown', __DIR__ . '/../GithubMarkdown.php'],
];

$src = [];
foreach($argv as $k => $arg) {
	if ($k == 0) {
		continue;
	}
	if ($arg[0] == '-') {
		$arg = explode('=', $arg);
		switch($arg[0]) {
			case '--flavor':
				if (isset($arg[1])) {
					if (isset($flavors[$arg[1]])) {
						require($flavors[$arg[1]][1]);
						$flavor = $flavors[$arg[1]][0];
					} else {
						echo "Error: Unknown flavor: " . $arg[1] . "\n";
						usage();
						exit(1);
					}
				} else {
					echo "Error: Incomplete argument --flavor!\n";
					usage();
					exit(1);
				}
			break;
			case '-h':
			case '--help':
				echo "PHP Markdown to HTML converter\n";
				echo "------------------------------\n\n";
				echo "by Carsten Brandt <mail@cebe.cc>\n\n";
				usage();
			break;
			default:
				echo "Error: Unknown argument " . $arg[0] . "\n";
				usage();
				exit(1);
		}
	} else {
		$src[] = $arg;
	}
}

if (empty($src)) {
	$markdown = file_get_contents("php://stdin");
} elseif (count($src) == 1) {
	$file = reset($src);
	if (!file_exists($file)) {
		echo "Error: File does not exist: $file\n";
		exit(1);
	}
	$markdown = file_get_contents($file);
} else {
	echo "Error: Converting multiple files is not yet supported.\n";
	usage();
	exit(1);
}

/** @var cebe\markdown\Parser $md */
$md = new $flavor();
echo $md->parse($markdown);

// functions

function usage() {
	global $argv;
	$cmd = $argv[0];
	echo <<<EOF
Usage:
    $cmd [--flavor=<flavor>] [file.md]

    --flavor  specifies the markdown flavor to use. If omitted the original markdown by John Gruber [1] will be used.
              Available flavors:

              gfm - Github flavored markdown [2]

    --help    shows this usage information.

    If no file is specified input will be read from STDIN.

Examples:

    Render a file with original markdown:

        $cmd README.md > README.html

    Render a file using gihtub flavored markdown:

        $cmd --flavor=gfm README.md > README.html

    Convert the original markdown description to html using STDIN:

        curl http://daringfireball.net/projects/markdown/syntax.text | $cmd > md.html


[1] http://daringfireball.net/projects/markdown/syntax
[2] https://help.github.com/articles/github-flavored-markdown

EOF;
	exit(1);
}
