/*
 * Copyright (C) 2005 - 2011 Jaspersoft Corporation. All rights reserved.
 * http://www.jaspersoft.com.
 *
 * Unless you have purchased  a commercial license agreement from Jaspersoft,
 * the following license terms  apply:
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License  as
 * published by the Free Software Foundation, either version 3 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 Affero  General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public  License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package com.jaspersoft.jasperserver.export.util;

import com.jaspersoft.jasperserver.api.JSException;
import com.jaspersoft.jasperserver.export.BaseExportImportCommand;
import com.jaspersoft.jasperserver.export.CommandHelpImpl;
import com.jaspersoft.jasperserver.export.CommandMetadataImpl;
import com.jaspersoft.jasperserver.export.Parameters;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class EncryptionUtils {
	public  static final String ARG_PASS = "pass";
	private static final String JS_ENCRYPTION_KEY = "JasperSoft";
	private static final String CRYPTOGRAPHIC_SERVICE = "Blowfish";
	private static final String MESSAGE_SOURCE_BUNDLE = "config/bundles/ji-export-messages";
	private static final String EXCEPTION_MESSAGE_SOURCE_BUNDLE = "config/bundles/jsexceptions_messages";


    public static void main(String[] args) throws Exception {

		Parameters exportParameters = CommandUtils.parse(args);

        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setUseCodeAsDefaultMessage(true);
        messageSource.setBasenames(new String[] {MESSAGE_SOURCE_BUNDLE,EXCEPTION_MESSAGE_SOURCE_BUNDLE});

        PrintStream out = System.out;
        try {
            if (exportParameters.hasParameter(ARG_PASS)) {
                String password = exportParameters.getParameterValue(ARG_PASS);
                // exit if empty string
                if (password == null) {
                    throw new JSException("jsexception.parameter.has.no.value", new Object[] {ARG_PASS});
                }
                // encryption
                byte[] encrypted = encrypt(password);

                // transform it to string to be able to store in .properties file
                String encPass = bytes2String(encrypted);

                // output
                out.println(messageSource.getMessage("ji.export.encryption.enc-pass", new String[]{password}, Locale.getDefault()));
                out.println(messageSource.getMessage("ji.export.encryption.add-string", null, Locale.getDefault()));
                out.println(com.jaspersoft.jasperserver.export.DecryptingPropertyPlaceholderConfigurer.JS_ENCRYPTED_PASSWORD_PROP + "=" + encPass);
                out.println();

    		} else {
                // printing help
                List commands = new ArrayList();
                commands.add(BaseExportImportCommand.ARG_HELP);
                commands.add(ARG_PASS);
           		CommandMetadataImpl metadata = new CommandMetadataImpl();
                metadata.setArgumentNames(commands);

                CommandHelpImpl help = new CommandHelpImpl();
                help.setMessageSource(messageSource);
                help.setStartMessage("ji.export.help.header");
                help.setArgDescriptionMessagePrefix("ji.export.arg.description.");
                help.setArgLinePrefix("  ");
                help.setArgLineSeparator("  ");
                help.printHelp(args[0], metadata, out);
            }

       	} catch (JSException e) {
			String message = messageSource.getMessage(e.getMessage(), e.getArgs(), Locale.getDefault());
			System.err.println(message);
		}
    }

    public static byte[] encrypt (String encString, byte[] raw) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, CRYPTOGRAPHIC_SERVICE);
        Cipher cipher = Cipher.getInstance(CRYPTOGRAPHIC_SERVICE);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        return cipher.doFinal(encString.getBytes());
    }

    public static String decrypt (byte[] encRead, byte[] raw) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, CRYPTOGRAPHIC_SERVICE);
        Cipher cipher = Cipher.getInstance(CRYPTOGRAPHIC_SERVICE);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        return new String(cipher.doFinal(encRead));
    }


    public static byte[]  encrypt (String encString) throws Exception {
        return encrypt(encString, JS_ENCRYPTION_KEY.getBytes());
    }

    public static String  getEncryptedString (String encString, byte[] raw) throws Exception {
        return bytes2String(encrypt(encString, raw));
    }
    public static String  getEncryptedString (String encString) throws Exception {
        return bytes2String(encrypt(encString, JS_ENCRYPTION_KEY.getBytes()));
    }


    public static String decrypt (byte[] encRead) throws Exception {
        return decrypt(encRead, JS_ENCRYPTION_KEY.getBytes());
    }
    public static String decrypt (String encString) throws Exception {
        return decrypt(string2Bytes(encString));
    }


    private static String bytes2String(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            if (i > 0) {
                sb.append(",");
            }
            String s = Integer.toHexString(bytes[i]);
            if (s.length() > 2) {
                s = s.substring(s.length() - 2);
            }
            if (s.length() < 2) {
                s = "0" + s;
            }
            sb.append("0x").append(s);
        }
        return sb.toString();
    }

    private static byte[] string2Bytes(String str) {
        String[] sa = str.split(",");
        byte[] bytes = new byte[sa.length];
        for (int i = 0; i < sa.length; i++) {
            bytes[i] = (byte) Short.decode(sa[i]).byteValue();
        }
        return bytes;
    }

}
