class Pfm::Command::Build

def build

def build
  # Zip the cookbooks for transfer
  Idlc::Workspace.zip_folder('./chef', "#{@workspace.tmp_dir}/cookbooks.zip")
  # Start the HTTP server to facilitate file transfers. This is to replace
  # WINRM for file transfers in Packer due to slowness. This function returns
  # the process id of the server instance.
  pid = Idlc::Build::Httpd.start(@workspace.tmp_dir)
  # #start will return twice when forking the HTTP server off, once for the
  # parent and once for the child. When the child return, the pid is nil. We want
  # to skip that run.
  unless pid.nil?
    # Pass some ENV vars for Packer
    @build_config.add_build_var_v2('aws_region', SETTINGS['AWS_REGION'])
    @build_config.add_build_var_v2('app_release', @config[:app_release])
    @build_config.add_build_var_v2('build_uuid', SecureRandom.uuid.to_s)
    @build_config.add_build_var_v2('build_number', @config[:build_number])
    @build_config.add_build_var_v2('httpd_server', Idlc::Build::Httpd.private_ip.to_s)
    @build_config.add_build_var_v2('httpd_port', ENV['HTTPD_PORT'])
    @build_config.add_build_var_v2('cookbooks_zip', "#{@workspace.tmp_dir}/cookbooks.zip")
    begin
      Packer::Binary.build("#{@build_config.dump_build_vars} #{@config[:build_template]}")
      Idlc::Build::Httpd.stop(pid)
      Dir.chdir(build_base_dir)
    rescue
      Idlc::Build::Httpd.stop(pid)
      Dir.chdir(build_base_dir)
      raise BuildFailure, 'The build finished with errors'
    end
  end
  Dir.chdir(build_base_dir)
end