/*
 * Hash.cs --
 *
 * Copyright (c) 2007-2012 by Joe Mistachkin.  All rights reserved.
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 * RCS: @(#) $Id: $
 */

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using Eagle._Attributes;
using Eagle._Components.Private;
using Eagle._Components.Public;
using Eagle._Constants;
using Eagle._Containers.Public;
using Eagle._Interfaces.Public;

namespace Eagle._Commands
{
    [ObjectId("66a2a9aa-1024-4199-b6d9-097c2662acd7")]
    [CommandFlags(CommandFlags.Safe | CommandFlags.NonStandard)]
    [ObjectGroup("string")]
    internal sealed class _Hash : Core
    {
        public _Hash(
            ICommandData commandData
            )
            : base(commandData)
        {
            // do nothing.
        }

        #region IEnsemble Members
        private static readonly EnsembleDictionary subCommands = new EnsembleDictionary(new string[] {
            "keyed", "mac", "normal"
        });

        public override EnsembleDictionary SubCommands
        {
            get { return subCommands; }
        }
        #endregion

        #region IExecute Members
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            ReturnCode code;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if (arguments.Count >= 2)
                    {
                        string subCommand = arguments[1];
                        bool tried = false;

                        code = ScriptOps.TryExecuteSubCommandFromEnsemble(
                            this, interpreter, clientData, arguments, true,
                            false, ref subCommand, ref tried, ref result);

                        if ((code == ReturnCode.Ok) && !tried)
                        {
                            //
                            // NOTE: These algorithms are known to be supported by the framework.
                            //
                            //  Hash: MD5, RIPEMD160, SHA, SHA1, SHA256, SHA384,
                            //        SHA512
                            //
                            //  HMAC: HMACMD5, HMACRIPEMD160, HMACSHA1, HMACSHA256,
                            //        HMACSHA384, HMACSHA512
                            //
                            // Keyed: MACTripleDES
                            //
                            switch (subCommand)
                            {
                                case "keyed":
                                    {
                                        if (arguments.Count >= 4)
                                        {
                                            OptionDictionary options = new OptionDictionary(
                                                new Option[] {
                                                new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-raw", null),
                                                new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-filename", null), /* COMPAT: Tcllib. */
                                                new Option(null, OptionFlags.MustHaveValue, Index.Invalid, Index.Invalid, "-encoding", null),
                                                new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, Option.EndOfOptions, null)
                                            });

                                            int argumentIndex = Index.Invalid;

                                            code = interpreter.GetOptions(options, arguments, 0, 2, Index.Invalid, false, ref argumentIndex, ref result);

                                            if (code == ReturnCode.Ok)
                                            {
                                                if ((argumentIndex != Index.Invalid) &&
                                                    ((argumentIndex + 2) <= arguments.Count) &&
                                                    ((argumentIndex + 3) >= arguments.Count))
                                                {
                                                    Variant value = null;
                                                    bool raw = false;

                                                    if (options.IsPresent("-raw"))
                                                        raw = true;

                                                    bool isFileName = false;

                                                    if (options.IsPresent("-filename", ref value))
                                                        isFileName = true;

                                                    string encodingName = null;

                                                    if (options.IsPresent("-encoding", ref value))
                                                        encodingName = value.ToString();

                                                    Encoding encoding = null;

                                                    if (encodingName != null)
                                                    {
                                                        code = Interpreter.GetEncoding(
                                                            interpreter, encodingName, ref encoding, ref result);
                                                    }

                                                    if (code == ReturnCode.Ok)
                                                    {
                                                        //
                                                        // NOTE: If no encoding was specified, use the
                                                        //       default.
                                                        //
                                                        if (encoding == null)
                                                            encoding = Channel.BinaryEncoding;

                                                        try
                                                        {
                                                            using (KeyedHashAlgorithm algorithm =
                                                                    KeyedHashAlgorithm.Create(arguments[argumentIndex]))
                                                            {
                                                                if (algorithm != null)
                                                                {
                                                                    algorithm.Initialize();

                                                                    if ((argumentIndex + 3) == arguments.Count)
                                                                        algorithm.Key = encoding.GetBytes(
                                                                            arguments[argumentIndex + 2]);

                                                                    if (isFileName)
                                                                    {
                                                                        Stream stream = null;

                                                                        try
                                                                        {
                                                                            code = RuntimeOps.NewStream(
                                                                                interpreter, arguments[argumentIndex + 1],
                                                                                FileMode.Open, FileAccess.Read, ref stream,
                                                                                ref result);

                                                                            if (code == ReturnCode.Ok)
                                                                            {
                                                                                if (raw)
                                                                                {
                                                                                    result = new ByteList(
                                                                                        algorithm.ComputeHash(stream));
                                                                                }
                                                                                else
                                                                                {
                                                                                    result = FormatOps.Hash(
                                                                                        algorithm.ComputeHash(stream));
                                                                                }
                                                                            }
                                                                        }
                                                                        finally
                                                                        {
                                                                            if (stream != null)
                                                                            {
                                                                                stream.Close();
                                                                                stream = null;
                                                                            }
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        if (raw)
                                                                        {
                                                                            result = new ByteList(
                                                                                algorithm.ComputeHash(encoding.GetBytes(
                                                                                    arguments[argumentIndex + 1])));
                                                                        }
                                                                        else
                                                                        {
                                                                            result = FormatOps.Hash(
                                                                                algorithm.ComputeHash(encoding.GetBytes(
                                                                                    arguments[argumentIndex + 1])));
                                                                        }
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    result = String.Format(
                                                                        "unsupported keyed hash algorithm \"{0}\"",
                                                                        arguments[argumentIndex]);

                                                                    code = ReturnCode.Error;
                                                                }
                                                            }
                                                        }
                                                        catch (Exception e)
                                                        {
                                                            Engine.SetExceptionErrorCode(interpreter, e);

                                                            result = e;
                                                            code = ReturnCode.Error;
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    if ((argumentIndex != Index.Invalid) &&
                                                        Option.LooksLikeOption(arguments[argumentIndex]))
                                                    {
                                                        result = OptionDictionary.BadOption(options, arguments[argumentIndex]);
                                                    }
                                                    else
                                                    {
                                                        result = String.Format(
                                                            "wrong # args: should be \"{0} {1} ?options? algorithm string ?key?\"",
                                                            this.Name, subCommand);
                                                    }

                                                    code = ReturnCode.Error;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            result = String.Format(
                                                "wrong # args: should be \"{0} {1} ?options? algorithm string ?key?\"",
                                                this.Name, subCommand);

                                            code = ReturnCode.Error;
                                        }
                                        break;
                                    }
                                case "mac":
                                    {
                                        if (arguments.Count >= 4)
                                        {
                                            OptionDictionary options = new OptionDictionary(
                                                new Option[] {
                                                new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-raw", null),
                                                new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-filename", null), /* COMPAT: Tcllib. */
                                                new Option(null, OptionFlags.MustHaveValue, Index.Invalid, Index.Invalid, "-encoding", null),
                                                new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, Option.EndOfOptions, null)
                                            });

                                            int argumentIndex = Index.Invalid;

                                            code = interpreter.GetOptions(options, arguments, 0, 2, Index.Invalid, false, ref argumentIndex, ref result);

                                            if (code == ReturnCode.Ok)
                                            {
                                                if ((argumentIndex != Index.Invalid) &&
                                                    ((argumentIndex + 2) <= arguments.Count) &&
                                                    ((argumentIndex + 3) >= arguments.Count))
                                                {
                                                    Variant value = null;
                                                    bool raw = false;

                                                    if (options.IsPresent("-raw"))
                                                        raw = true;

                                                    bool isFileName = false;

                                                    if (options.IsPresent("-filename", ref value))
                                                        isFileName = true;

                                                    string encodingName = null;

                                                    if (options.IsPresent("-encoding", ref value))
                                                        encodingName = value.ToString();

                                                    Encoding encoding = null;

                                                    if (encodingName != null)
                                                    {
                                                        code = Interpreter.GetEncoding(
                                                            interpreter, encodingName, ref encoding, ref result);
                                                    }

                                                    if (code == ReturnCode.Ok)
                                                    {
                                                        //
                                                        // NOTE: If no encoding was specified, use the
                                                        //       default.
                                                        //
                                                        if (encoding == null)
                                                            encoding = Channel.BinaryEncoding;

                                                        try
                                                        {
                                                            using (HMAC algorithm = HMAC.Create(arguments[argumentIndex]))
                                                            {
                                                                if (algorithm != null)
                                                                {
                                                                    algorithm.Initialize();

                                                                    if ((argumentIndex + 3) == arguments.Count)
                                                                        algorithm.Key = encoding.GetBytes(
                                                                            arguments[argumentIndex + 2]);

                                                                    if (isFileName)
                                                                    {
                                                                        Stream stream = null;

                                                                        try
                                                                        {
                                                                            code = RuntimeOps.NewStream(
                                                                                interpreter, arguments[argumentIndex + 1],
                                                                                FileMode.Open, FileAccess.Read, ref stream,
                                                                                ref result);

                                                                            if (code == ReturnCode.Ok)
                                                                            {
                                                                                if (raw)
                                                                                {
                                                                                    result = new ByteList(
                                                                                        algorithm.ComputeHash(stream));
                                                                                }
                                                                                else
                                                                                {
                                                                                    result = FormatOps.Hash(
                                                                                        algorithm.ComputeHash(stream));
                                                                                }
                                                                            }
                                                                        }
                                                                        finally
                                                                        {
                                                                            if (stream != null)
                                                                            {
                                                                                stream.Close();
                                                                                stream = null;
                                                                            }
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        if (raw)
                                                                        {
                                                                            result = new ByteList(
                                                                                algorithm.ComputeHash(encoding.GetBytes(
                                                                                    arguments[argumentIndex + 1])));
                                                                        }
                                                                        else
                                                                        {
                                                                            result = FormatOps.Hash(
                                                                                algorithm.ComputeHash(encoding.GetBytes(
                                                                                    arguments[argumentIndex + 1])));
                                                                        }
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    result = String.Format(
                                                                        "unsupported hmac algorithm \"{0}\"",
                                                                        arguments[argumentIndex]);

                                                                    code = ReturnCode.Error;
                                                                }
                                                            }
                                                        }
                                                        catch (Exception e)
                                                        {
                                                            Engine.SetExceptionErrorCode(interpreter, e);

                                                            result = e;
                                                            code = ReturnCode.Error;
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    if ((argumentIndex != Index.Invalid) &&
                                                        Option.LooksLikeOption(arguments[argumentIndex]))
                                                    {
                                                        result = OptionDictionary.BadOption(options, arguments[argumentIndex]);
                                                    }
                                                    else
                                                    {
                                                        result = String.Format(
                                                            "wrong # args: should be \"{0} {1} ?options? algorithm string ?key?\"",
                                                            this.Name, subCommand);
                                                    }

                                                    code = ReturnCode.Error;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            result = String.Format(
                                                "wrong # args: should be \"{0} {1} ?options? algorithm string ?key?\"",
                                                this.Name, subCommand);

                                            code = ReturnCode.Error;
                                        }
                                        break;
                                    }
                                case "normal":
                                    {
                                        if (arguments.Count >= 4)
                                        {
                                            OptionDictionary options = new OptionDictionary(
                                                new Option[] {
                                                new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-raw", null),
                                                new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-filename", null), /* COMPAT: Tcllib. */
                                                new Option(null, OptionFlags.MustHaveValue, Index.Invalid, Index.Invalid, "-encoding", null),
                                                new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, Option.EndOfOptions, null)
                                            });

                                            int argumentIndex = Index.Invalid;

                                            code = interpreter.GetOptions(options, arguments, 0, 2, Index.Invalid, false, ref argumentIndex, ref result);

                                            if (code == ReturnCode.Ok)
                                            {
                                                if ((argumentIndex != Index.Invalid) && ((argumentIndex + 2) == arguments.Count))
                                                {
                                                    Variant value = null;
                                                    bool raw = false;

                                                    if (options.IsPresent("-raw"))
                                                        raw = true;

                                                    bool isFileName = false;

                                                    if (options.IsPresent("-filename", ref value))
                                                        isFileName = true;

                                                    string encodingName = null;

                                                    if (options.IsPresent("-encoding", ref value))
                                                        encodingName = value.ToString();

                                                    Encoding encoding = null;

                                                    if (encodingName != null)
                                                    {
                                                        code = Interpreter.GetEncoding(
                                                            interpreter, encodingName, ref encoding, ref result);
                                                    }

                                                    if (code == ReturnCode.Ok)
                                                    {
                                                        //
                                                        // NOTE: If no encoding was specified, use the
                                                        //       default.
                                                        //
                                                        if (encoding == null)
                                                            encoding = Channel.BinaryEncoding;

                                                        try
                                                        {
                                                            using (HashAlgorithm algorithm =
                                                                    HashAlgorithm.Create(arguments[argumentIndex]))
                                                            {
                                                                if (algorithm != null)
                                                                {
                                                                    algorithm.Initialize();

                                                                    if (isFileName)
                                                                    {
                                                                        Stream stream = null;

                                                                        try
                                                                        {
                                                                            code = RuntimeOps.NewStream(
                                                                                interpreter, arguments[argumentIndex + 1],
                                                                                FileMode.Open, FileAccess.Read, ref stream,
                                                                                ref result);

                                                                            if (code == ReturnCode.Ok)
                                                                            {
                                                                                if (raw)
                                                                                {
                                                                                    result = new ByteList(
                                                                                        algorithm.ComputeHash(stream));
                                                                                }
                                                                                else
                                                                                {
                                                                                    result = FormatOps.Hash(
                                                                                        algorithm.ComputeHash(stream));
                                                                                }
                                                                            }
                                                                        }
                                                                        finally
                                                                        {
                                                                            if (stream != null)
                                                                            {
                                                                                stream.Close();
                                                                                stream = null;
                                                                            }
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        if (raw)
                                                                        {
                                                                            result = new ByteList(
                                                                                algorithm.ComputeHash(encoding.GetBytes(
                                                                                    arguments[argumentIndex + 1])));
                                                                        }
                                                                        else
                                                                        {
                                                                            result = FormatOps.Hash(
                                                                                algorithm.ComputeHash(encoding.GetBytes(
                                                                                    arguments[argumentIndex + 1])));
                                                                        }
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    result = String.Format(
                                                                        "unsupported hash algorithm \"{0}\"",
                                                                        arguments[argumentIndex]);

                                                                    code = ReturnCode.Error;
                                                                }
                                                            }
                                                        }
                                                        catch (Exception e)
                                                        {
                                                            Engine.SetExceptionErrorCode(interpreter, e);

                                                            result = e;
                                                            code = ReturnCode.Error;
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    if ((argumentIndex != Index.Invalid) &&
                                                        Option.LooksLikeOption(arguments[argumentIndex]))
                                                    {
                                                        result = OptionDictionary.BadOption(options, arguments[argumentIndex]);
                                                    }
                                                    else
                                                    {
                                                        result = String.Format(
                                                            "wrong # args: should be \"{0} {1} ?options? algorithm string\"",
                                                            this.Name, subCommand);
                                                    }

                                                    code = ReturnCode.Error;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            result = String.Format(
                                                "wrong # args: should be \"{0} {1} ?options? algorithm string\"",
                                                this.Name, subCommand);

                                            code = ReturnCode.Error;
                                        }
                                        break;
                                    }
                                default:
                                    {
                                        result = ScriptOps.BadSubCommand(null, null, subCommand, this, null, null);
                                        code = ReturnCode.Error;
                                        break;
                                    }
                            }
                        }
                    }
                    else
                    {
                        result = "wrong # args: should be \"hash option ?arg ...?\"";
                        code = ReturnCode.Error;
                    }
                }
                else
                {
                    result = "invalid argument list";
                    code = ReturnCode.Error;
                }
            }
            else
            {
                result = "invalid interpreter";
                code = ReturnCode.Error;
            }

            return code;
        }
        #endregion
    }
}
