<?php

if ( 'cli' != php_sapi_name() || $argc < 3 )
	exit;

$user     = $argv[1];
$password = $argv[2];

$bin  = dirname( __FILE__ );
$repo = 'https://core.svn.wordpress.org';
$yui  = $bin . '/yuicompressor-2.4.2.jar';
if ( ! file_exists( $yui ) )
	exit;

$yui = "java -jar $yui -v";

$start = microtime( true );

if ( ! is_dir( "$bin/trunk" ) )
	echo `svn checkout --ignore-externals $repo/trunk $bin/trunk`;

chdir( "$bin/trunk" );

// Just in case.
echo `svn cleanup; svn revert -R *`;

$find_rev = `svn up --ignore-externals`;

if ( ! preg_match( '/^At revision (\d+)\.$/', $find_rev, $rev ) )
	exit( 'svn up failed.' . "\n" );
$rev = $rev[1];

// We can use this in the future. The bot can post warnings to Trac, for example.
$output = array();

foreach ( array( 'css', 'js' ) as $type ) {
	$files = explode( "\n", trim( `find . -name "*.dev.$type"` ) );
	foreach ( $files as $file ) {
		$file = substr( $file, 0, -strlen( ".dev.$type" ) );
		$result = trim( `$yui --type $type -o $file.$type $file.dev.$type 2>&1` );
		if ( false === strpos( $result, '[WARNING]' ) )
			$result = true;
		else
			$result = strstr( $result, '[WARNING]' );
		$output[ "$file.dev.$type" ] = $result;
	}
}

$diff = `svn stat --ignore-externals | grep ^M`;
$diff = explode( "\n", $diff );
foreach ( $diff as &$d )
	$d = trim( ltrim( $d, 'M' ) );
$diff = array_filter( $diff );

$stop = microtime(true) - $start;

if ( empty( $diff ) )
	exit( 'Nothing to commit.' . "\n" );

$version_php = file_get_contents( './wp-includes/version.php' );

// 3.4-alpha-12345 to 3.4-alpha-12346
if ( preg_match( "/wp_version = '(.*?)-(.*?)-(\d+)'/", $version_php, $matches ) )
	$version_php = preg_replace( "/wp_version = '(.*?)-(.*?)-(\d+)'/",
		'wp_version = \'$1-$2-' . ( $rev + 1 ) . "'", $version_php );
// 3.4-alpha to 3.4-alpha-12346
elseif ( preg_match( "/wp_version = '(.*?)-(.*?)'/", $version_php, $matches ) )
	$version_php = preg_replace( "/wp_version = '(.*?)-(.*?)'/",
		'wp_version = \'$1-$2-' . ( $rev + 1 ) . "'", $version_php );
// 3.4
else
	exit( "Stable release. Don't touch!" . "\n" );

file_put_contents( './wp-includes/version.php', $version_php );

$user     = escapeshellarg( $user );
$password = escapeshellarg( $password );
$msg      = escapeshellarg( 'Compress scripts/styles: ' . $matches[1] . '-' . $matches[2] . '-' . ( $rev + 1 ) . '.' );

#echo `svn diff`;
echo `svn commit -m --no-auth-cache --non-interactive --username $user --password $password $msg`;

exit( $msg . "\n" );