/*
 * This file is part of Vestige.
 *
 * Vestige is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Vestige 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Vestige.  If not, see <http://www.gnu.org/licenses/>.
 */

package fr.gaellalire.vestige.admin.ssh;

import static org.apache.sshd.common.util.KeyUtils.getKeyType;

import java.security.KeyPair;
import java.util.ArrayList;
import java.util.List;

import org.apache.sshd.common.keyprovider.FileKeyPairProvider;

/**
 * This host key provider loads private keys from the specified files. Note that this class has a direct dependency on BouncyCastle and won't work unless it has been correctly
 * registered as a security provider.
 * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
 */
public class FileKeyPairProviderWithAliases extends FileKeyPairProvider {

    public FileKeyPairProviderWithAliases(final String[] strings) {
        super(strings);
    }

    @Override
    public KeyPair loadKey(final String type) {
        String realType = type;
        if ("rsa-sha2-256".equals(type) || "rsa-sha2-512".equals(type)) {
            realType = "ssh-rsa";
        }
        Iterable<KeyPair> keys = loadKeys();
        for (KeyPair key : keys) {
            if (realType.equals(getKeyType(key))) {
                return key;
            }
        }
        return null;
    }

    public String getKeyTypes() {
        List<String> types = new ArrayList<String>();
        Iterable<KeyPair> keys = loadKeys();
        for (KeyPair key : keys) {
            String type = getKeyType(key);
            if (type != null && !types.contains(type)) {
                if ("ssh-rsa".equals(type)) {
                    types.add("rsa-sha2-256");
                    types.add("rsa-sha2-512");
                }
                types.add(type);
            }
        }
        StringBuilder sb = new StringBuilder();
        for (String type : types) {
            if (sb.length() > 0) {
                sb.append(",");
            }
            sb.append(type);
        }
        return sb.toString();
    }

}
