/***********************************************************************
 *
 *  Copyright (C) 2006 Novell, Inc. All Rights Reserved.
 *
 *  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; version 2.1
 *  of the License.
 *
 *  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
 *  Library 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, Novell, Inc.
 *
 *  To contact Novell about this file by physical or electronic mail,
 *  you may find current contact information at www.novell.com.
 *
 *  Author: Juan Carlos Luciani <jluciani@novell.com>
 *
 ***********************************************************************/

package com.novell.casa.authtoksvc;

/**
 *
 * Class for the creation and editing of authtoken.settings files.
 *
 */
public final class AuthTokenSettingsEditor implements IVerifySetting
{
   private static final String usage =
      "usage: AuthTokenSettingsEditor -op [settingName [settingValue]] -file settingsFilePath\n\n" +
      "   where:\n" +
      "      -op - Corresponds to one of the following operations:\n" +
      "         -create - Create new authtoken settings file\n" +
      "         -list   - List settings\n" +
      "         -get    - Get settings, must be followed by settingName parameter\n" +
      "         -set    - Set settings, must be followed by settingName and settingValue parameters\n" +
      "         -remove - Remove settings\n" +
      "      -file - Path the the authtoken settings file\n" +
      "      settingName - Name of the setting being retrieved or set\n" +
      "      settingValue - Value of the setting being set\n\n" +
      "   The following settings are valid:\n" +
      "      TokenLifetime\n" +
      "      LifetimeShorter\n";

   private static final String settings =
      "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
      "<settings>\n" +
      "</settings>\n";


   /**
    * Checks if the specified setting is valid.
    *
    * @param setting The name of the setting being checked.
    * @return        True if the specified setting is valid.
    */
   public boolean validSetting(String setting)
   {
      boolean result = false;

      if (setting.equalsIgnoreCase(AuthTokenConfig.TokenLifetime))
         result = true;
      else if (setting.equalsIgnoreCase(AuthTokenConfig.LifetimeShorter))
         result = true;
      else if (setting.equalsIgnoreCase(AuthTokenConfig.IdentityTokenType))
         result = true;
      else
         System.err.println("Invalid setting specified");

      return result;
   }

   /**
    * Checks if the specified setting is valid in conjunction
    * with the specified value.
    *
    * @param setting The name of the setting being checked.
    * @param value   The value of the specified setting.
    * @return        The formal name of the setting if found to be valid.
    */
   public String validSettingNameAndValue(String setting,
                                          String value)
   {
      String validSetting = null;

      if (setting.equalsIgnoreCase(AuthTokenConfig.TokenLifetime))
      {
         // Verify that we are dealing with a numeric value
         try
         {
            Integer.valueOf(value);

            // Good
            validSetting = AuthTokenConfig.TokenLifetime;
         }
         catch (NumberFormatException e)
         {
            System.err.println("Invalid setting value specified");
         }
      }
      else if (setting.equalsIgnoreCase(AuthTokenConfig.LifetimeShorter))
      {
         // Verify that we are dealing with a numeric value
         try
         {
            Integer.valueOf(value);

            // Good
            validSetting = AuthTokenConfig.LifetimeShorter;
         }
         catch (NumberFormatException e)
         {
            System.err.println("Invalid setting value specified");
         }
      }
      else if (setting.equalsIgnoreCase(AuthTokenConfig.IdentityTokenType))
      {
         // Always succeed
         validSetting = AuthTokenConfig.IdentityTokenType;
      }
      else
         System.err.println("Invalid setting specified");

      return validSetting;
   }

   /**
   *  Applications Entry Point.
   *
   * @param args  Arguments.
   */
   public static void main(String[] args)
   {
      String op = null;
      boolean opPerformed = false;
      boolean argumentsError = false;
      String filePath = null;
      String setting = null;
      String value = null;
      AuthTokenSettingsEditor editor = new AuthTokenSettingsEditor();

      // Process the command line arguments
      for (int i = 0; i < args.length; i++)
      {
         // Proceed based on the command
         if (args[i].equalsIgnoreCase("-file"))
         {
            // The next argument should contain the filepath
            if (args.length > (i + 1))
            {
               filePath = args[i + 1];
               i++;
            }
            else
            {
               argumentsError = true;
               break;
            }
         }
         else if (args[i].equalsIgnoreCase("-list"))
         {
            // List operation requested
            if (op == null)
            {
               op = "list";
            }
            else
            {
               argumentsError = true;
               break;
            }
         }
         else if (args[i].equalsIgnoreCase("-create"))
         {
            // List operation requested
            if (op == null)
            {
               op = "create";
            }
            else
            {
               argumentsError = true;
               break;
            }
         }
         else if (args[i].equalsIgnoreCase("-get"))
         {
            // Get setting operation requested
            if (op == null)
            {
               op = "get";

               // The next argument should contain the setting name
               if (args.length > (i + 1))
               {
                  setting = args[i + 1];
                  i++;
               }
               else
               {
                  argumentsError = true;
                  break;
               }
            }
            else
            {
               argumentsError = true;
               break;
            }
         }
         else if (args[i].equalsIgnoreCase("-set"))
         {
            // Set setting operation requested
            if (op == null)
            {
               op = "set";

               // The next two arguments should contain the setting name
               // and the setting value.
               if (args.length > (i + 2))
               {
                  setting = args[i + 1];
                  value = args[i + 2];
                  i += 2;
               }
               else
               {
                  argumentsError = true;
                  break;
               }
            }
            else
            {
               argumentsError = true;
               break;
            }
         }
         else if (args[i].equalsIgnoreCase("-remove"))
         {
            // Remove setting operation requested
            if (op == null)
            {
               op = "remove";

               // The next argument should contain the setting name
               if (args.length > (i + 1))
               {
                  setting = args[i + 1];
                  i++;
               }
               else
               {
                  argumentsError = true;
                  break;
               }
            }
            else
            {
               argumentsError = true;
               break;
            }
         }
         else
         {
            argumentsError = true;
         }
      }

      // Proceed based on the specified parameters
      if (argumentsError == false)
      {
         if (filePath != null && op != null)
         {
            System.err.println("Dealing with settings file: " + filePath);

            // Proceed based on the operation requested
            if (op.compareTo("list") == 0)
            {
               opPerformed = SettingsFileUtil.performListOperation(filePath);
            }
            else if (op.compareTo("create") == 0)
            {
               opPerformed = SettingsFileUtil.performCreateOperation(filePath, settings);
            }
            else if (op.compareTo("get") == 0)
            {
               opPerformed = SettingsFileUtil.performGetOperation(filePath, setting, editor);
            }
            else if (op.compareTo("set") == 0)
            {
               opPerformed = SettingsFileUtil.performSetOperation(filePath, setting, value, editor);
            }
            else if (op.compareTo("remove") == 0)
            {
               opPerformed = SettingsFileUtil.performRemoveOperation(filePath, setting, editor);
            }
            else
            {
               System.err.println("Tool error");
            }
         }
         else
         {
            argumentsError = true;
         }
      }

      // Display the usage string if we encountered an error with the
      // command line arguments.
      if (argumentsError)
         System.out.print(usage);

      // Set the exit code appropriatedly
      if (opPerformed)
         System.exit(0);
      else
         System.exit(1);
   }
}
