package org.apache.sshd.fs.test;

import org.apache.sshd.client.ClientBuilder;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.apache.sshd.common.keyprovider.KeyPairProvider;
import org.apache.sshd.fs.SftpFileSystem;
import org.apache.sshd.fs.SftpFileSystemProvider;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.jupiter.api.Test;
import org.xbib.io.sshd.eddsa.EdDSASecurityProvider;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyPair;
import java.security.Provider;
import java.security.Security;
import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.logging.Logger;

public class SFTPFileSystemTest {

    private static final Logger logger = Logger.getLogger(SFTPFileSystemTest.class.getName());

    static {
        // load bouncy castle provider (and other security providers)
        for (Provider p : ServiceLoader.load(Provider.class)) {
            if (Security.getProvider(p.getName()) == null) {
                Security.addProvider(p);
            }
        }
    }

    @Test
    public void init() throws Exception {
        Map<String, String> env = new HashMap<>();
        env.put("username", "joerg");
        URI uri = URI.create("sftp://xbib.org");
        SshClient sshClient = ClientBuilder.builder().build();
        Path privateKey = Paths.get("/Users/joerg/.ssh/id_ed25519");
        KeyPairProvider keyPairProvider = new FileKeyPairProvider(privateKey);
        keyPairProvider.loadKeys(null).forEach(sshClient::addPublicKeyIdentity);
        for (String keyType : keyPairProvider.getKeyTypes(null)) {
            logger.info("found key type = " + keyType);
        }
        KeyPair keyPair = keyPairProvider.loadKey(null, "ssh-ed25519");
        sshClient.addPublicKeyIdentity(keyPair);
        sshClient.setNioWorkers(1);
        sshClient.start();
        SftpFileSystem fileSystem = new SftpFileSystemProvider(sshClient).newFileSystem(uri, env);
        // ...
        sshClient.stop();
    }
}
