require 'net/ssh'
require 'pathname'
namespace :create_site do
  desc "Delete Site Script"
  task :delete_site,[:site_construct_id] => :environment do |task,args|
    @site_construct = SiteConstruct.find(args.site_construct_id)
    site_server = SiteServer.where(:server_name=>@site_construct.server_type).first
    ip = site_server.ip
    server_port = site_server.port
    user = site_server.account
    password = site_server.password
    @password = password
    begin
      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|
        @site_construct.update!(:infos=>[])
        if @site_construct.status != "closed"
          update_infos("Closing site #{@site_construct.site_name}...")
        end
        exec_ssh_command_by_sudo(ssh,"kill -s TERM `cat tmp/pids/unicorn.pid`")
        exec_ssh_command_by_sudo(ssh,"kill -s TERM `fuser tmp/unicorn.sock`")
        update_infos("deleting database for #{@site_construct.site_name}")
        db_name = exec_ssh_command_by_sudo(ssh,"echo `cat #{@site_construct.path}/#{@site_construct.get_site_name}/config/mongoid.yml | grep 'database'`").split("database:").last.strip
        exec_ssh_command_by_sudo(ssh,"bash -l -c 'echo \"db.dropDatabase()\" | mongo --shell \'#{db_name}\''")
        update_infos("finish deleting database for #{@site_construct.site_name}")
        update_infos("deleting orbit4-5 at #{@site_construct.path}/#{@site_construct.site_name}")
        exec_ssh_command_by_sudo(ssh,"rm -rf #{@site_construct.path}/#{@site_construct.get_site_name}")
        update_infos("finish deleting #{@site_construct.site_name}")
        update_infos("deleting nginx for #{@site_construct.site_name}")
        exec_ssh_command_by_sudo(ssh,"rm -f #{@site_construct.nginx_file.gsub(" ","\\ ")}")
        update_infos("finish deleting nginx setting for #{@site_construct.site_name}")
        update_infos("restarting nginx")
        exec_ssh_command_by_sudo(ssh,"service nginx restart")
        update_infos("finish restarting nginx")
        @site_construct.update(:status =>"")
      end
    rescue =>e
      @site_construct.update(:status =>"error",:infos=>@site_construct.infos.push("#{e}"))
    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
  end
  def update_infos(info)
    puts info
    @site_construct.infos = @site_construct.infos.push(info)
    @site_construct.save!
    return @site_construct.infos
  end
end