/*
 *	  GetFreePath.java
 *    A task to find a free folder to put something in
 *
 *    Copyright (C) 2008 New Zealand Digital Library, http://www.nzdl.org
 *
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
package org.greenstone.anttasks;

import org.apache.tools.ant.*;
import org.apache.tools.ant.taskdefs.*;
import java.io.File;

/**
 * Returns a path, based on the given path, which does not exist on the filesystem
 * If the given path doesn't exist on the system, just returns the path
 * If the given path does exist, return the path appended with "(n)" where
 * where n is the lowest possible integer greater than 1 which would result in a
 * path that does not exist on the file system.
 */
public class GetFreePath extends Task {

	private File path = null;
	private String property = null;

	/**
	 * for testing
	 */
	public static void main( String[] args ) {
		GetFreePath gfp = new GetFreePath();
		gfp.setPath( new File(args[0]) );
		gfp.setProperty( args[1] );
		gfp.execute();
	}

	public void execute() {

		//check both attributes set
		if ( path == null ) {
			throw new BuildException( "Error - No path specified !!" );
		}

		if ( property == null ) {
			throw new BuildException( "Error - No property specified !!" );
		}

		//find a free path
		File returnPath = new File(path.getPath());
		for ( int i=2; returnPath.exists(); i++ ) {
			returnPath = new File(path.getPath() + "(" + i + ")" );
		}

		//set the found path in the project
		Project pr = getProject();
		if ( pr != null && pr.getProperty(property) == null ) {
			pr.setProperty( property, returnPath.getPath() );
		}
		System.out.println(returnPath.getPath());
		

	}

   
	public void setPath(File path) {
		this.path = path;
	}

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

}
