/*--
  This file is a part of ZetaGrid, a simple and secure Grid Computing
  kernel.

  Copyright (c) 2001-2004 Sebastian Wedeniwski.  All rights reserved.

  Use in source and binary forms, with or without modification,
  are permitted provided that the following conditions are met:

  1. The source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.

  2. The origin of this software must not be misrepresented; you must 
     not claim that you wrote the original software.  If you plan to
     use this software in a product, please contact the author.

  3. Altered source versions must be plainly marked as such, and must
     not be misrepresented as being the original software. The author
     must be informed about these changes.

  4. The name of the author may not be used to endorse or promote 
     products derived from this software without specific prior written 
     permission.

  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

  Version 1.9.0, February 8, 2004

  This program is based on the work of:
     S. Wedeniwski
--*/


package zeta.tool;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import zeta.util.DatabaseUtils;
import zeta.util.ThrowableHandler;

public class ZetaMigration {
  public static void main(String args[]) {
    try {
      if (args.length == 3) {
        ZetaMigration m = new ZetaMigration(args[1], args[2]);
        m.check(Integer.parseInt(args[0]), true);
        m.close();
      } else System.err.println("USAGE: java zeta.tool.ZetaMigration <server id> <user> <password>");
    } catch (Exception e) {
      ThrowableHandler.handle(e);
    }
  }

  public ZetaMigration(String user, String password) throws Exception {
    Class.forName("COM.ibm.db2.jdbc.app.DB2Driver").newInstance();
    connection = DriverManager.getConnection("jdbc:db2:zeta", user, password);
  }

  private String check(int serverId, boolean change) throws Exception {
    Statement stmt = null;
    try {
      stmt = connection.createStatement();
      Map wsMap = new HashMap();
      ResultSet rs = stmt.executeQuery("SELECT id,hostname FROM zeta.workstation WHERE server_id=" + serverId);
      while (rs.next()) {
        wsMap.put(new Integer(rs.getInt(1)), rs.getString(2));
      }
      rs.close();
      Map userMap = new HashMap();
      rs = stmt.executeQuery("SELECT user_id,workstation_id,MAX(stop) FROM zeta.computation comp, zeta.result res WHERE comp.task_id=res.task_id AND comp.work_unit_id=res.work_unit_id AND server_id=" + serverId + " GROUP BY user_id,workstation_id ORDER BY MAX(stop) DESC");
      while (rs.next()) {
        Integer userId = new Integer(rs.getInt(1));
        List list = (List)userMap.get(userId);
        if (list == null) {
          list = new ArrayList();
          userMap.put(userId, list);
        }
        list.add(new Object[] { new Integer(rs.getInt(2)), rs.getTimestamp(3) });
      }
      rs.close();
      StringBuffer wsIds = new StringBuffer(100);
      Iterator i = userMap.keySet().iterator();
      while (i.hasNext()) {
        Integer userId = (Integer)i.next();
        List list = (List)userMap.get(userId);
        int l = list.size();
        for (int j = 0; j < l; ++j) {
          Integer wsId = (Integer)((Object[])list.get(j))[0];
          String hostname = (String)wsMap.get(wsId);
          for (int k = j+1; k < l; ++k) {
            Integer wsId2 = (Integer)((Object[])list.get(k))[0];
            if (hostname.equalsIgnoreCase((String)wsMap.get(wsId2))) {
              System.out.println("ws id=" + wsId + " (" + hostname + ") replace ws id=" + wsId2 + " (" + wsMap.get(wsId2) + ')');
              rs = stmt.executeQuery("SELECT DISTINCT user_id FROM zeta.computation WHERE server_id=" + serverId + " AND NOT user_id=" + userId + " AND workstation_id=" + wsId2);
              if (rs.next()) {
                System.out.println("PROBLEM user id=" + rs.getInt(1));
                System.exit(1);
              }
              rs.close();
              if (change) {
                DatabaseUtils.executeAndLogUpdate(serverId, stmt, "UPDATE zeta.computation SET workstation_id=" + wsId2 + " WHERE server_id=" + serverId + " AND workstation_id=" + wsId);
              }
              if (wsIds.length() > 0) {
                wsIds.append(',');
              }
              wsIds.append(((Object[])list.get(k))[0]);
            }
          }
        }
      }
      System.out.println("wsIds=" + wsIds.toString());
      return wsIds.toString();
    } catch (SQLException e) {
      ThrowableHandler.handle(e);
    } finally {
      DatabaseUtils.close(stmt);
    }
    return null;
  }

  private void change(int serverId, String wsIds) throws Exception {
    Statement stmt = null;
    Statement stmt2 = null;
    try {
      stmt = connection.createStatement();
      stmt2 = connection.createStatement();
      ResultSet rs = stmt.executeQuery("SELECT DISTINCT id,hostname,key FROM zeta.computation comp, zeta.workstation ws WHERE comp.server_id=ws.server_id AND comp.workstation_id=ws.id AND ws.server_id=" + serverId + ((wsIds.length() == 0)? "" : " AND id NOT IN (" + wsIds + ')'));
      while (rs.next()) {
        String key = rs.getString(3);
        if (key == null) {
          DatabaseUtils.executeAndLogUpdate(serverId, stmt2, "UPDATE zeta.workstation SET hostname='" + rs.getString(2).toLowerCase() + "' WHERE server_id=" + serverId + " AND id=" + rs.getInt(1));
        } else {
          DatabaseUtils.executeAndLogUpdate(serverId, stmt2, "UPDATE zeta.workstation SET (hostname,key)=('" + rs.getString(2).toLowerCase() + "','" + key.toLowerCase() + "') WHERE server_id=" + serverId + " AND id=" + rs.getInt(1));
        }
      }
      rs.close();
    } catch (SQLException e) {
      ThrowableHandler.handle(e);
    } finally {
      DatabaseUtils.close(stmt);
      DatabaseUtils.close(stmt2);
    }
  }

  private void close() {
    DatabaseUtils.close(connection);
    connection = null;
  }

  private Connection connection = null;
}