require_relative "worker"

class CreateServerWorker < Worker

  # options must contain 'server_attrs', 'owner'
  def perform(options)
    logger.info "Running create server worker"
    server_attrs = options.fetch('server_attrs')
    owner = options.fetch('owner')

    call() do |out, task|
      project = Devops::Model::Project.find_with_environment(server_attrs["project"], server_attrs["environment"])
      env = project.environment(server_attrs["environment"])
      category = env.get_category(server_attrs["category"])

      set_task_data({
        "created_by" => owner,
        "project" => project.id,
        "environment" => env.id,
        "category" => category.id,
        "type" => Devops::Model::JobTask::CREATE_SERVER_TYPE
      })

      server_options = {}
      executor = Devops::Executor::ServerExecutor.new(nil, out, owner)
      executor.project = project
      executor.job_task = task
      executor.environment = env
      executor.category = category
      msg = "\nOperation completed successfully"
      res = begin
        res = executor.create_server(server_attrs)
        server = executor.server
        unless server.nil?
          task.server_id = server.id
          task.save
        end
        if server_attrs["without_bootstrap"]
          out.puts "Without bootstraping"
        else
          executor.waiting_ssh
          info = executor.deploy_info(server_options)
          executor.bootstrap_server server_options, info
          executor.deploy_server server_options, info
        end
        0
      rescue Devops::Exception::BootstrapError => e
        DevopsLogger.logger.error(msg = e.message)
        unless options[:skip_rollback]
          executor.roll_back
          server.delete
        end
        out.flush
        e.error_code
      rescue Devops::Exception::ServerOperationError => e
        msg = e.message
        DevopsLogger.logger.error msg
        e.error_code
      rescue => e
        msg = "Failed while creating server\nUnexpected error: #{e.message}\n#{e.backtrace.join("\n")}"
        DevopsLogger.logger.error msg
        -10
      end
      out.puts msg
      out.flush
      res
    end
  end

end
