#!/usr/bin/env php
<?php
/**
 * Look for WordPress readme in current directory or above and convert into markdown readme in same directory
 * @version 1.0.1
 * @author Weston Ruter <weston@xwp.co> (@westonruter)
 * @copyright Copyright (c) 2014, XWP <https://xwp.co/>
 * @license GPLv2+
 */

try {
	if ( php_sapi_name() !== 'cli' ) {
		throw new Exception( 'Only allowed in CLI mode.' );
	}

	$readme_txt_path = null;
	while ( true ) {
		foreach ( array( 'readme.txt', 'README.txt' ) as $readme_filename ) {
			if ( file_exists( $readme_filename ) ) {
				$readme_txt_path = realpath( $readme_filename );
				break;
			}
		}

		$old_cwd = getcwd();
		if ( ! empty( $readme_txt_path ) || ! chdir( '..' ) || getcwd() === $old_cwd ) {
			break;
		}
	}
	if ( empty( $readme_txt_path ) ) {
		throw new Exception( 'Failed to find a readme.txt or README.txt above the current working directory.' );
	}

	$readme_root = dirname( $readme_txt_path );
	$readme_md_path = preg_replace( '/txt$/', 'md', $readme_txt_path );

	require_once __DIR__ . '/class-wordpress-readme-parser.php';

	$readme = new WordPress_Readme_Parser( array( 'path' => $readme_txt_path ) );

	$md_args = array();
	$github_account_repo = null;
	$github_url_regex = '#.+github\.com[:/](?P<account_repo>[^/]+/[^/]+?)(?:\.git)?$#';
	$remote_urls = array();
	foreach ( explode( "\n", `git remote -v | grep fetch` ) as $remote_line ) {
		$remote_line = trim( $remote_line );
		if ( $remote_line ) {
			list( $name, $url ) = preg_split( '/\s+/', $remote_line );
			$remote_urls[ $name ] = $url;
		}
	}
	if ( ! empty( $remote_urls['origin'] ) && preg_match( $github_url_regex, $remote_urls['origin'], $matches ) ) {
		$github_account_repo = $matches['account_repo'];
	} else {
		foreach ( $remote_urls as $remote_name => $remote_url ) {
			if ( preg_match( $github_url_regex, $remote_url, $matches ) ) {
				$github_account_repo = $matches['account_repo'];
				break;
			}
		}
	}
	if ( $github_account_repo ) {
		if ( file_exists( $readme_root . '/.travis.yml' ) ) {
			$md_args['travis_ci_url'] = "https://travis-ci.org/$github_account_repo";
		}
		if ( file_exists( $readme_root . '/.coveralls.yml' ) ) {
			$md_args['coveralls_badge_src'] = "https://coveralls.io/repos/$github_account_repo/badge.png";
			$md_args['coveralls_url'] = "https://coveralls.io/r/$github_account_repo";
		}
		if ( file_exists( $readme_root . '/.gitter' ) ) {
			$md_args['gitter_url'] = "https://gitter.im/$github_account_repo";
		}
	}
	$markdown = $readme->to_markdown( $md_args );

	$is_written = file_put_contents( $readme_md_path, $markdown );
	if ( ! $is_written ) {
		throw new Exception( sprintf( 'Failed to write to %s', $readme_md_path ) );
	}
	fwrite( STDERR, 'Successfully converted WordPress README to Markdown' . PHP_EOL );
	fwrite( STDOUT, $readme_md_path . PHP_EOL );
}
catch( Exception $e ) {
	fwrite( STDERR, $e->getMessage() . PHP_EOL );
	exit( 1 );
}
