require 'net/ssh'
require 'pathname'
namespace :create_site do
  desc "Delete databases Script"
  task :delete_dbs,[:server_name,:dbs] => :environment do |task,args|
    site_server = SiteServer.where(:server_name=>args.server_name).first
    ip = site_server.ip
    server_port = site_server.port
    user = site_server.account
    password = site_server.password
    @password = password
    dbs = args.dbs.split
    begin 
      Net::SSH.start(ip , user , { password: password, port: server_port}) do |ssh|
      end
    rescue Net::SSH::HostKeyMismatch
      system("ssh-keygen -f \"$HOME/.ssh/known_hosts\" -R #{ip}")
    rescue Errno::ENOTTY
      system("ssh-add \"$HOME/.ssh/id_rsa\"")
    end
    Net::SSH.start(ip , user , { password: password, port: server_port}) do |ssh|
      dbs.each do |db|
        puts "deleting database #{db}"
        exec_ssh_command_by_sudo(ssh,"bash -l -c 'echo \"db.dropDatabase()\" | mongo --shell \'#{db}\''")
        puts "finish deleting database #{db}"
      end
    end
    puts "finished deleting databases rake"
  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_infos(info)
    puts info
    @site_construct.infos = @site_construct.infos.push(info)
    @site_construct.save!
    return @site_construct.infos
  end
end