require 'net/ssh'
require 'net/ssh/proxy/http'
require 'pathname'
namespace :create_site do
  desc "Test ssh"
  task :test_ssh,[] => :environment do |task,args|
      @site_server = SiteServer.where(:server_name=>'dev').first
      Net::SSH.start(@site_server.ip , @site_server.account , { password: @site_server.password, port: @site_server.port}) do |ssh|
        exec_ssh_command_by_sudo_and_see_output_for_test(ssh,"bash -l -c 'cd orbit_sites/design3;bundle update'")
      end
  end
  def exec_ssh_command_and_see_output_for_test(session,command)
    outputs = []
    puts "execing #{command}"
    session.open_channel do |channel|
      channel.request_pty do |channel, success|
        channel.exec("LANG=en.UTF8 #{command}") do |ch, success|
          abort "could not execute command: #{command}" unless success
          channel.on_data do |ch, data|
            outputs.push(data)
            print "#{data}"
            if data.to_s.include? "sudo password:"
              channel.send_data "#{@site_server.password}\n"
            end
          end
          channel.on_close do |ch|
            puts "finish execing #{command}"
          end
        end
      end
    end
    session.loop
    return outputs
  end
  def exec_ssh_command_by_sudo_and_see_output_for_test(session,command)
    outputs = exec_ssh_command_and_see_output_for_test(session,command)
    if outputs.join("\n").include?("Permission denied")
      exec_ssh_command_and_see_output_for_test(session,"sudo -p 'sudo password:' #{command}")
    end
  end
  def update_thread_infos(info)
    puts info
    @thread.status["infos"] = @thread.status["infos"].push(info)
    @thread.save!
    return @thread.status["infos"]
  end
end