/*
 *	  AddGreenstoneUserToDatabase.java
 *    A task to add a user to the Greenstone User Database
 *
 *    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;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import lib.Crypt;

public class AddGreenstoneUserToDatabase extends Task {

	private File txt2db = null;
	private File usersDb = null;
	private String username = null;
	private String password = null;
	private String groups = null;
	private String comment = null;

	public static void main( String[] args ) {
		AddGreenstoneUserToDatabase agu = new AddGreenstoneUserToDatabase();
		agu.setTxt2db( new File(args[0]) );
		agu.setUsersDb( new File(args[1]) );
		agu.setUsername( args[2] );
		agu.setPassword( args[3] );
		agu.setGroups( args[4] );
		agu.setComment( args[5] );
		agu.execute();
	}

	public void execute() {

		if ( txt2db == null ) { throw new BuildException( "Error - txt2db not specified!!" ); }
		if ( usersDb == null ) { throw new BuildException( "Error - usersDb not specified!!" ); }
		if ( username == null ) { throw new BuildException( "Error - username not specified!!" ); }
		if ( password == null ) { throw new BuildException( "Error - password not specified!!" ); }
		if ( groups == null ) { throw new BuildException( "Error - groups not specified!!" ); }
		if ( comment == null ) { comment = ""; }

		String encryptedPassword = Crypt.crypt("Tp", password);

		long usersDbFileLastModified = 0;
		try {
			// Get the users.db file's last modification date so it can be reset afterwards
			usersDbFileLastModified = usersDb.lastModified();
		} catch (Exception exception) {
			throw new BuildException( "Failed to get the last modified time of the users db" );
        }

		Process txt2dbProcess = null;
		try {
			// Write directly to the txt2db process to append to the users.db file
			String[] cmdAndArgs = { txt2db.getAbsolutePath(), "-append", usersDb.getAbsolutePath() };
			txt2dbProcess = Runtime.getRuntime().exec( cmdAndArgs );
		} catch ( Exception e ) {
			System.err.println( e.getMessage() );
			e.printStackTrace();
			throw new BuildException( "Failed to execute the txt2db process" );
        }

		BufferedWriter txt2dbIn = null;
		try {
			txt2dbIn = new BufferedWriter(new OutputStreamWriter(txt2dbProcess.getOutputStream()));
		} catch (Exception exception) {
			throw new BuildException( "Failed to get an input stream" );
        }

		try {
			txt2dbIn.write("[" + username + "]"); txt2dbIn.newLine();
			txt2dbIn.write("<comment>" + comment); txt2dbIn.newLine();
			txt2dbIn.write("<enabled>true"); txt2dbIn.newLine();
			txt2dbIn.write("<groups>" + groups); txt2dbIn.newLine();
			txt2dbIn.write("<password>" + encryptedPassword); txt2dbIn.newLine();
			txt2dbIn.write("<username>" + username); txt2dbIn.newLine();
			txt2dbIn.write("----------------------------------------------------------------------"); txt2dbIn.newLine();

			txt2dbIn.flush();
			txt2dbIn.close();
			txt2dbProcess.waitFor();

		} catch (Exception exception) {
			throw new BuildException( "Failed to add the user to the user database" );
        }

		try {
			usersDb.setLastModified(usersDbFileLastModified);
		} catch (Exception exception) {
			throw new BuildException( "Failed to reset the last modified time of the users db" );
        }

    }

	public void setTxt2db( File txt2db ) { this.txt2db = txt2db; }
	public void setUsersDb( File usersDb ) { this.usersDb = usersDb; }
	public void setUsername( String username ) { this.username = username; }
	public void setPassword( String password ) { this.password = password; }
	public void setGroups( String groups ) { this.groups = groups; }
	public void setComment( String comment ) { this.comment = comment; }

}
