/** This is used to set the attribute value of an entry in the Manifest file.
  * there are 3 attributes:
  * viz filename,property & value
  * All attributes are required.
  * Example:
  * If you have a file called Manifest.mf
  * which looks like this:
  * Manifest-Version: 1.1
  * Package-Version: 2.1
  * ...............etc
  * and now you run
  * <SetManifestProperty filename="Manifest.mf" property="Package-Version" value="NIGHTLY"/>
  * the result will be
  * Manifest-Version: 1.1
  * Package-Version: NIGHTLY
  * ..................etc
  * @author Aarti Chandnani achandnani@xuma.com
  * 02 May 2001
  **/
package org.apache.tools.ant.taskdefs.optional;


import org.apache.tools.ant.*;
import java.util.jar.*;
import java.io.*;
import java.util.*;


public class SetManifestProperty extends Task
{
	private String filename;
	private String property;
	private String value;

	/**
	  * Sets the filename attribute.
     */

	public void setFilename(String filename)
	{
		this.filename = filename;
	}//setFilename

	/**
	  * Sets the property attribute
	  **/

	public void setProperty(String property)
	{
		this.property = property;
	}//setProperty


	/**
	  * Sets the value attribute
	  **/
	public void setValue(String value)
	{
		this.value = value;
	}//setValue

	/**
	 * Does the work.
	 *
	 * @exception BuildException if someting goes wrong with the build
     */

	public void execute() throws BuildException
	{
		try
		{


			FileInputStream fi = new FileInputStream(filename);
			Manifest man = new Manifest(fi);
			Attributes at = new Attributes(man.getMainAttributes());
			at.putValue(property,value);
			fi.close();
			Set se = at.entrySet();
			Iterator it = se.iterator();
			int i =0;
			while(it.hasNext())
			{
				String old = new String(it.next().toString());
				String newone = new String(old.replace('=',':'));
				StringBuffer sub = new StringBuffer(newone);
				sub = sub.insert(newone.indexOf(':')+1," ");
				newone = new String(sub);
				if(i==0)
					write(filename,newone);
				else
					append(filename,newone);
				i++;
			}//while
		}//try
		catch (Exception e)
		{
			System.out.println("caught exception " + e);
			throw new BuildException(e);
		}//catch
	}//execute

	private  void write(String filename,String s) throws Exception
	{
		PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename)));
		out.print(s.trim() + "\n");
		out.close();
	}//write

	private void append(String filename,String s) throws Exception
	{
		PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename,true)));
		out.println(s);
		out.close();
	}//append
}//class

