<?php

namespace ModulesGarden\ProxmoxAddon\App\Factory;

use ModulesGarden\ProxmoxAddon\App\Repositories\ServerConfigurationRepository;
use phpseclib3\Crypt\PublicKeyLoader;
use phpseclib3\Crypt\RSA;
use phpseclib3\Net\SSH2;

class Ssh2Factory
{

    /**
     * @param ServerConfigurationRepository $serConf
     * @return SSH2
     * @throws \Exception
     */
    public function fromServerConfiguration(ServerConfigurationRepository $serConf){

        if(!$serConf->sshHost){
            throw  new \InvalidArgumentException("SSH Host is empty");
        }
        $ssh2 = new SSH2($serConf->sshHost, $serConf->sshPort );
        $keyOrPassword =  $serConf->getSshPassword();
        //private key
        if($serConf->hasSshKey()){
             $keyOrPassword = PublicKeyLoader::load($serConf->getSshKey());
        }
        //login
        if(!$ssh2->login($serConf->sshUser, $keyOrPassword)){
            throw  new \Exception(sprintf("Login to SSH Host: %s failed", $serConf->sshHost));
        }
        return $ssh2;
    }


}