/*
 * Copyright (c) 2004-2017, by Alex Leigh.
 * All rights reserved.
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE
 * The copyright notice above does not evidence any
 * actual or intended publication of such source code.
 */

package lc.mecha.key;

import lc.mecha.log.MechaLogger;
import lc.mecha.log.MechaLoggerFactory;
import lc.mecha.util.UniversalJob;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * Implementation of a key loader meant to store key material for use with foreign systems.
 *
 * @author Alex Leigh
 */
public class UnsecureKeyLoader {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(UnsecureKeyLoader.class);
    private final Properties props;
    private final File file;

    /**
     * Create a new key loader. The filename specified by the environment variable
     * <code>A6V_UKLS</code> will be used.
     *
     * @throws IOException
     */
    public UnsecureKeyLoader() throws IOException {
        this(new File(System.getenv("A6V_UKLS")));
    }

    public UnsecureKeyLoader(final File file) throws IOException {
        this.file = file;
        if (!file.exists()) file.createNewFile();
        props = new Properties();
        props.load(new FileInputStream(file));
    }

    public static void main(final String... args) throws IOException {

        if (args.length != 3) {
            logger.error("Usage: UnsecureKeyLoader file key value");
            System.exit(UniversalJob.RET_BADARGS);
        }

        final UnsecureKeyLoader key = new UnsecureKeyLoader(new File(args[0]));
        key.setKey(args[1], args[2]);

        logger.info("OK");
    }

    private void save() throws IOException {
        props.store(new FileOutputStream(file), null);
    }

    public String getKey(final String name) {
        return props.getProperty(name);
    }

    public void setKey(final String name, final String material) throws IOException {
        props.setProperty(name, material);
        save();
    }
}
