module SshCommands

  def ssh_test server, params
    res, code = ssh_execute(server, "test #{params}")
    code == 0
  end

  def ssh_execute server, cmd
    key_path = server[:private_key]
    ssh_cmd = "ssh -i #{key_path} #{server[:remote_user]}@#{server[:host]} '#{cmd}'"
    DevopsLogger.logger.info "Ssh command: #{ssh_cmd}"
    res = `#{ssh_cmd}`
    return res, $?
  end

 def self.ssh_with_status out, cert_path, user, ip, remote_cmd
    cmd = "ssh -t -i #{cert_path} #{user}@#{ip} \"#{(user == "root" ? remote_cmd : "sudo #{remote_cmd}")}\""
    out << "\nCommand: '#{cmd}'\n"
    out.flush if out.respond_to?(:flush)
    status = nil
    IO.popen(cmd + " 2>&1") do |c|
      buf = ""
      while line = c.gets do
        out << line
        buf = line
      end
      c.close
      status = $?.to_i
      r = buf.scan(/exit\scode\s([0-9]{1,3})/)[0]
      unless r.nil?
        status = r[0].to_i
      end
    end
    status
  end

end
