require_relative "worker"

class UnbootstrapWorker < Worker

  # @options
  # 'server_id':       required
  # 'owner':              required
  def perform(options)
    server_id = options.fetch('server_id')
    owner = options.fetch('owner')

    call() do |out, task|
      server = Devops::Model::Server.find(server_id)
      set_task_data({
        "created_by" => owner,
        "project" => server.project,
        "environment" => server.environment,
        "server_id" => server.id,
        "category" => server.category,
        "type" => Devops::Model::JobTask::UNBOOTSTRAP_TYPE
      })
      executor = Devops::Executor::ServerExecutor.new(server, out, owner)
      executor.job_task = task
      status = begin
        out << "Trying to unbootstrap server '#{server.id}' with CM name '#{server.cm_name}'\n\n"
        executor.unbootstrap_server
        0
      rescue Devops::Exception::ServerOperationError => e
        msg = e.message
        DevopsLogger.logger.error msg
        e.error_code
      end
      out.puts msg
      out.flush
      status
    end
  end

end

