#!/usr/bin/php -q
# Line above: our PHP is in /usr/bin, not in /usr/local/bin
<?php
	# Mantis - a php based bugtracking system
	# Copyright (C) 2000 - 2002  Kenzaburo Ito - kenito@300baud.org
	# Copyright (C) 2002 - 2004  Mantis Team   - mantisbt-dev@lists.sourceforge.net
	# This program is distributed under the terms and conditions of the GPL
	# See the README and LICENSE files for details

	# --------------------------------------------------------
	# $Id$
	# --------------------------------------------------------

	global $g_bypass_headers;
	$g_bypass_headers = 1;
	require_once( dirname( dirname( __FILE__ ) ) . DIRECTORY_SEPARATOR . 'core.php' );

	# Make sure this script doesn't run via the webserver
	# @@@ This is a hack to detect php-cgi, there must be a better way.
	if ( isset( $_SERVER['SERVER_PORT'] ) ) {
		echo "checkin.php is not allowed to run through the webserver.\n";
		exit( 1 );
	}
	# Check that the username is set and exists
	### our shell/cvs usernames are our mantis login names, so record under that
	# WAS: $t_username = config_get( 'source_control_account' );
	$t_username = exec('whoami');

	if ( is_blank( $t_username ) || ( user_get_id_by_name( $t_username ) === false ) ) {
		echo "Invalid source control account ('$t_username').\n";
		exit( 1 );
	}

	# Regular expression used to detect version tags
	$g_source_control_versiontag_regexp = "/^([\D_]+)\d[\d_]+/i";

	# Detect references to issues + concat all lines to have the comment log.
	$t_versiontag_regexp = $g_source_control_versiontag_regexp;
	
	$t_newtag = $argv[1];
		
	if ( ($argv[2]=='add') 
	&& preg_match( $t_versiontag_regexp, $t_newtag, $t_matches ) ) {
		# Login as source control user
		if ( !auth_attempt_script_login( $t_username ) ) {
			echo "Unable to login\n";
			exit( 1 );
		}
		
		for ( $i = 0; $i < count( $t_matches[0] ); ++$i ) {
			$t_project = $t_matches[1];
			$t_projects = project_get_all_rows();

			foreach ($t_projects as $t_project_info) {
				if (isset($t_project_info['versiontag_prefix'])
				&& ($t_project_info['versiontag_prefix'] == $t_project)) {
					version_add( $t_project_info['id'], $t_newtag);					
				};
			};
		}
	}

	exit( 0 );
?>
