/*
 * Copyright (C) 2024 ScalAgent Distributed Technologies
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 * 
 * This library 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
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA.
 *
 * Initial developer(s): ScalAgent Distributed Technologies
 * Contributor(s): 
 */
package fr.dyade.aaa.tools.backup;

import java.io.File;
import java.io.IOException;
import java.util.regex.Pattern;

import fr.dyade.aaa.agent.AgentServer;
import fr.dyade.aaa.util.backup.RestoreFile;

public class BackupTool {
  
  public final static String HELP_CMD = "help";
  
  public final static String BACKUP_CMD = "backup";
  
  public final static String LIST_CMD = "list";
  public final static String EXTRACT_CMD = "extract";
  public final static String DUMP_CMD = "dump";

  public final static String PERSISTENCE_DIRECTORY = "PERSISTENCE_DIRECTORY";
  public final static String DEFAULT_PERSISTENCE_DIRECTORY = "./data/jorammq/s0";
  
  public final static String EXTRACT_DIRECTORY = "EXTRACT_DIRECTORY";
  public final static String DEFAULT_EXTRACT_DIRECTORY = ".";
  
  public final static String FILTER_PROPERTY = "FILTER";
  
  public final static String DEBUG_OPT = "DEBUG";
  
  public static void main(String args[]) {
    boolean debug = Boolean.getBoolean(DEBUG_OPT);
    if (args.length != 2) {
      usage();
      return;
    }

    // Verify that the command is valid
    String command = args[0];
    if (!BACKUP_CMD.equals(command) && !LIST_CMD.equals(command) && !EXTRACT_CMD.equals(command) && !DUMP_CMD.equals(command)) {
      usage();
      return;
    }
    
    String backupPath = args[1];
    
    Pattern filter = null;
    String regexp = System.getProperty(FILTER_PROPERTY);
    if ((regexp != null) && !regexp.isEmpty())
      filter = Pattern.compile(regexp);
    
    if (BACKUP_CMD.equals(command)) {
      try {
        String serverDataDirPath = System.getProperty(PERSISTENCE_DIRECTORY, DEFAULT_PERSISTENCE_DIRECTORY);
        AgentServer.externalBackup(serverDataDirPath, backupPath);
      } catch (Exception exc) {
        if (debug)
          exc.printStackTrace();
        else
          System.err.println(exc.getMessage());
      }
    } else if (LIST_CMD.equals(command)) {
      try {
        RestoreFile.list(new File(backupPath), filter);
      } catch (IOException exc) {
        if (debug)
          exc.printStackTrace();
        else
          System.err.println(exc.getMessage());
      }
    } else if (EXTRACT_CMD.equals(command)) {
      try {
        File dir;

        String dpath = System.getProperty(EXTRACT_DIRECTORY, DEFAULT_EXTRACT_DIRECTORY);
        dir = new File(dpath);
        if (dir.exists()) {
          if (!dir.isDirectory())
            throw new IOException(dpath + " is not a directory");
        } else {
          if (!dir.mkdirs())
            throw new IOException("can not create directory " + dpath);
        }
        RestoreFile.extract(new File(backupPath), filter, dir);
      } catch (IOException exc) {
        if (debug)
          exc.printStackTrace();
        else
          System.err.println(exc.getMessage());
      }
    } else if (DUMP_CMD.equals(command)) {
      try {
        RestoreFile.dump(new File(backupPath), filter);
      } catch (IOException exc) {
        if (debug)
          exc.printStackTrace();
        else
          System.err.println(exc.getMessage());
      }
    }
  }
  
  /**
   * Prints the help message.
   */
  public static void usage() {
    System.out.println("usage:\njava -D" + PERSISTENCE_DIRECTORY+ "=<path> " + "-D" + EXTRACT_DIRECTORY + "=<path> -DSILENT=true\n" +
        "     -jar backuptool.jar  [" + HELP_CMD + "|" + BACKUP_CMD + "|" + LIST_CMD + "|" +  EXTRACT_CMD + "|" +  DUMP_CMD + "] <parameter>\n");

    System.err.println("Options and parameters, set by Java environment variable (\"-Dproperty=value\" in\n" + 
        "command line):");
    System.err.println("  - " + PERSISTENCE_DIRECTORY + ": Path to directory containing the persistence data.\n" + 
        "    If it is not defined uses the default directory.");
    System.err.println("  - " + EXTRACT_DIRECTORY + ": Path to directory where to restore the data. If it is \n" + 
        "    not defined uses the current directory.");
    System.err.println("  - " + FILTER_PROPERTY + ": Regular expression allowing to filter objets in '" + LIST_CMD + "', '" +  EXTRACT_CMD + "'\n" +
        "    and '" +  DUMP_CMD + "' commands. If it is not defined all objects are processed.");
    System.err.println("\nCommands:\n" + 
        "  - " + HELP_CMD + ": prints the usage message.\n" + 
        "  - " + BACKUP_CMD + ": backup the persistence in the backup file. Be careful, the\n" + 
        "    corresponding broker must be stopped.\n" +
        "    The backup file is created in the directory specified in parameter, its\n" +
        "    name is \"backup-<date>.tbck\"\n" +
        "  - " + LIST_CMD + ": lists the objects contained in the backup file specified in\n" +
        "    parameter.\n" + 
        "  - " + EXTRACT_CMD + ": extracts the objects contained in the backup file specified in\n" +
        "    parameter.\n" + 
        "  - " + DUMP_CMD + ": dumps the objects contained in the backup file specified in parameter.\n");
  }

}
