#!/usr/bin/env php
<?php
/**
 * @copyright Copyright (c) 2014 Carsten Brandt
 * @license https://github.com/cebe/markdown/blob/master/LICENSE
 * @link https://github.com/cebe/markdown#readme
 */

$composerAutoload = [
    __DIR__ . '/../vendor/autoload.php', // standalone with "composer install" run
    __DIR__ . '/../../../autoload.php', // script is installed as a composer binary
];
foreach ($composerAutoload as $autoload) {
    if (file_exists($autoload)) {
        require($autoload);
        break;
    }
}

// Send all errors to stderr
ini_set('display_errors', 'stderr');

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

$full = false;
$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 {
						error("Unknown flavor: " . $arg[1], "usage");
					}
				} else {
					error("Incomplete argument --flavor!", "usage");
				}
			break;
			case '--link-style':
				if (isset($arg[1])) {
					if ($arg[1] === 'href' || $arg[1] === 'footnote') {
						$linkStyle = $arg[1];
					} else {
						error("Unknown link style: " . $arg[1], "usage");
					}
				} else {
					error("Incomplete argument --link-style!", "usage");
				}
			break;
			case '--full':
				$full = true;
				break;
			case '-h':
			case '--help':
				echo "PHP Markdown to LaTeX converter\n";
				echo "------------------------------\n\n";
				echo "by Carsten Brandt <mail@cebe.cc>\n\n";
				usage();
			break;
			default:
				error("Unknown argument " . $arg[0], "usage");
		}
	} else {
		$src[] = $arg;
	}
}

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

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

if ($full) {
	echo <<<'TEX'
\documentclass[a4paper, 12pt]{article}

% english and utf8
\usepackage[british]{babel}
\usepackage[utf8]{inputenc}

% url support
\usepackage{url}

% make links clickable
\usepackage{hyperref}

% code listings
\usepackage{listings}
\usepackage{color}

\definecolor{codebg}{rgb}{0.9,0.9,0.9}
\definecolor{mygreen}{rgb}{0,0.6,0}
\definecolor{mygray}{rgb}{0.5,0.5,0.5}
\definecolor{mymauve}{rgb}{0.58,0,0.82}

\lstset{%
  backgroundcolor=\color{codebg},   % choose the background color; you must add \usepackage{color} or \usepackage{xcolor}
  basicstyle=\footnotesize,        % the size of the fonts that are used for the code
  breakatwhitespace=false,         % sets if automatic breaks should only happen at whitespace
  breaklines=true,                 % sets automatic line breaking
  captionpos=b,                    % sets the caption-position to bottom
  commentstyle=\color{mygreen},    % comment style
% deletekeywords={...},            % if you want to delete keywords from the given language
  escapeinside={\%*}{*)},          % if you want to add LaTeX within your code
  extendedchars=true,              % lets you use non-ASCII characters; for 8-bits encodings only, does not work with UTF-8
% frame=single,                    % adds a frame around the code
  keepspaces=true,                 % keeps spaces in text, useful for keeping indentation of code (possibly needs columns=flexible)
  keywordstyle=\color{blue},       % keyword style
% language=Octave,                 % the language of the code
% morekeywords={*,...},            % if you want to add more keywords to the set
  numbers=left,                    % where to put the line-numbers; possible values are (none, left, right)
  numbersep=5pt,                   % how far the line-numbers are from the code
  numberstyle=\tiny\color{mygray}, % the style that is used for the line-numbers
  rulecolor=\color{black},         % if not set, the frame-color may be changed on line-breaks within not-black text (e.g. comments (green here))
  showspaces=false,                % show spaces everywhere adding particular underscores; it overrides 'showstringspaces'
  showstringspaces=false,          % underline spaces within strings only
  showtabs=false,                  % show tabs within strings adding particular underscores
  stepnumber=1,                    % the step between two line-numbers. If it's 1, each line will be numbered
  stringstyle=\color{mymauve},     % string literal style
  tabsize=2,                       % sets default tabsize to 2 spaces
  title=\lstname                   % show the filename of files included with \lstinputlisting; also try caption instead of title
}

\lstdefinelanguage{json}{
	morekeywords={},
	sensitive=false,
	morestring=[b]",
}

% include images
\usepackage{graphicx}

% support github markdown strikethrough
% http://tex.stackexchange.com/questions/23711/strikethrough-text
\usepackage{ulem}

\begin{document}

TEX;
	echo $tex;
	echo '\end{document}' . "\n";
} else {
	echo $tex;
}

// functions

/**
 * Display usage information
 */
function usage() {
	global $argv;
	$cmd = $argv[0];
	echo <<<EOF
Usage:
    $cmd [--flavor=<flavor>] [--full] [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]
              extra - Markdown Extra [3]

    --link-style  specifies how links are being rendered:

              footnote (default) - render all links with a footnote, which contains the full URL of the link. This is good for printing the PDF.
              href - render all links with a hyperref, similar to HTML, the link target is not visible in this case.

    --full    ouput a full TEX document with document class, begin and end document. If not given, only the parsed markdown will be output.

    --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.tex

    Render a file using gihtub flavored markdown:

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

    Convert the original markdown description to html using STDIN:

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


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

EOF;
	exit(1);
}

/**
 * Send custom error message to stderr
 * @param $message string
 * @param $callback mixed called before script exit
 * @return void
 */
function error($message, $callback = null) {
	$fe = fopen("php://stderr", "w");
	fwrite($fe, "Error: " . $message . "\n");

	if (is_callable($callback)) {
		call_user_func($callback);
	}

	exit(1);
}
