require 'net/ssh'
require 'pathname'
require 'fileutils'
namespace :create_site do
  desc "Update multiple nginx setting"
  task :update_multiple_nginx_setting,[:server_name] => :environment do |task,args|
    Multithread.where(:key=>'update_multiple_nginx_setting').each{|thread| thread.destroy if (thread.status["status"] == "error" || thread.status["status"] == "finish")}
    Multithread.where(:key=>'update_multiple_nginx_setting').destroy
    @thread = Multithread.where(:key=>'update_multiple_nginx_setting').first
    @type = "exec_all"
    if @thread.nil?
      begin
        @thread = Multithread.create(:key=>'update_multiple_nginx_setting',:status=>{"infos"=>[],"status"=>"execing"})
        if( args.server_name.nil? rescue true)
            site_servers = SiteServer.all.where(:active=>true).to_a
        else
            site_servers = SiteServer.where(:server_name=>args.server_name).to_a
        end
        site_servers.each do |site_server|
          next if (site_server.need_update_site_ids.count == 0)
          @site_server = site_server
          update_thread_infos("<span style='color: skyblue;'>"+@site_server.server_name+"</span>")
          @password = @site_server.password
          begin
            begin 
              Net::SSH.start(@site_server.ip , @site_server.account , { password: @site_server.password, port: @site_server.port}) do |ssh|
              end
            rescue Net::SSH::HostKeyMismatch
              system("ssh-keygen -f \"$HOME/.ssh/known_hosts\" -R #{@site_server.ip}")
            rescue Errno::ENOTTY
              system("ssh-add \"$HOME/.ssh/id_rsa\"")
            rescue => e
              update_thread_infos(e.to_s)
              next
            end
            Net::SSH.start(@site_server.ip , @site_server.account , { password: @site_server.password, port: @site_server.port}) do |ssh|
              need_update_sites = SiteConstruct.where(:id.in=>@site_server.need_update_site_ids).to_a
              need_update_sites.each do |site_construct|
                update_thread_infos("<span style='color: blueviolet;'>Changing "+site_construct.site_name+" nginx...</span>")
                change_construct_nginx(ssh,site_construct,true)
              end
              @site_server.need_update_site_ids = []
              @site_server.save
            end
          end
        end
        @thread.update(:status=>@thread.status.merge({"status"=>"finish"}))
      rescue => e
        puts [e,e.backtrace]
        @thread.update(:status=>{"infos"=>@thread.status["infos"].push(e.to_s),"status"=>"error"})
      end
    end
  end
  def exec_ssh_command_by_sudo(session,command)
    output = session.exec!("echo '#{@password}' | sudo -S #{command}")
    # output = session.exec!("echo '#{@password}' | sudo -S -s #{command}")
    if output.include?("sudo:") && output.include?("command not found")
      output = session.exec!(command)
    end
    return output.encode!("UTF-8", :invalid => :replace, :undef => :replace, :replace => '')
  end
  def update_thread_infos(info)
    puts info
    @thread.status["infos"] = @thread.status["infos"].push(info)
    @thread.save!
    return @thread.status["infos"]
  end
end