// Copyright (c) 2009, Jens Peter Secher <jpsecher@gmail.com>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

//
// Process stdin to stdout by expanding macro values defined in Constants.
//

typedef Substitution =
{
	regExp : String,
	expander : Void -> String
}

class MacroExpand
{
	public static function main()
	{
		var substitutions : Array<Substitution> =
		[
			{ regExp : "{Package}", expander : Constants.packageName },
			{ regExp : "{BuildPackage}", expander : Constants.buildPackage },
			{ regExp : "{ImportOrig}", expander : Constants.importOrig },
			{ regExp : "{ImportDsc}", expander : Constants.importDsc },
			{ regExp : "{PristineTar}", expander : Constants.pristineTar },
			{ regExp : "{Port}", expander : Constants.port },
			{ regExp : "{TagVersion}", expander : Constants.tagVersion },
			{ regExp : "{Version}", expander : Constants.version },
			{ regExp : "{UpstreamVersion}", expander : Constants.upstream_version },
			{ regExp : "{VendorVersion}", expander : Constants.vendor_version },
		];
		var input = Sys.stdin();
		var stdout = Sys.stdout();
		while( true )
		{
			try
			{
				stdout.writeString
				(
					Lambda.fold( substitutions, expand, input.readLine() )
				);
				stdout.writeString( "\n" );				 
			}
			catch( e : Dynamic )
			{
				// End of file.
				break;
			}
		}
		Sys.exit( 0 );
	}
	
	static function expand( substitution : Substitution, input : String	) : String
	{		
		var regExp = new EReg( substitution.regExp, "g" );
		return regExp.replace( input, substitution.expander() );
	}
}
