require_relative "worker"

class BootstrapWorker < Worker

  # @options
  # 'server_id':       required
  # 'owner':              required
  # 'skip_rollback':      optional
  # 'deploy_info':        optional
  # 'deployers':          optional
  # 'bootstrap_template': optional
  # 'chef_environment':   optional
  # 'config':             optional, whatever this parameter really means
  def perform(options)
    server_id = options.fetch('server_id')
    owner = options.fetch('owner')

    bootstrap_options = {}
    ['bootstrap_template', 'run_list', 'cm_name'].each do |key|
      bootstrap_options[key.to_sym] = options[key] if options.key?(key)
    end

    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::BOOTSTRAP_TYPE
      })
      executor = Devops::Executor::ServerExecutor.new(server, out, owner)
      executor.job_task = task

      status = begin
        info = executor.deploy_info(bootstrap_options)
        executor.bootstrap_server bootstrap_options, info
        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

