package cn.reghao.bnt.web.devops.builder.tool.repo;

import org.eclipse.jgit.transport.sshd.SshdSessionFactory;
import org.eclipse.jgit.util.FS;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;

/**
 * https://stackoverflow.com/questions/67767455/setting-ssh-keys-to-use-with-jgit-with-ssh-from-apache-sshd
 *
 * @author reghao
 * @date 2023-03-13 09:06:54
 */
public class CustomSshSessionFactory extends SshdSessionFactory {
    public static final Path SSH_DIR = Path.of(FS.DETECTED.userHome() + "/.ssh");

    private final Path privateKeyFile;
    private final byte[] privateKey;

    public CustomSshSessionFactory(String privateKey) {
        //this.privateKeyFile = Path.of("rsa_prikey", SSH_DIR.toString());
        this.privateKeyFile = Path.of("/tmp/rsa_prikey");
        this.privateKey = privateKey.getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public File getSshDirectory() {
        try {
            return Files.createDirectories(SSH_DIR).toFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // Return paths to private key files
    @Override
    protected List<Path> getDefaultIdentities(File sshDir) {
        try {
            Files.write(privateKeyFile, privateKey);
            return Collections.singletonList(privateKeyFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Collections.emptyList();
    }
}
