File: packaging.rb

package info (click to toggle)
ruby-passenger 4.0.53-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 28,668 kB
  • ctags: 70,512
  • sloc: cpp: 264,280; ruby: 25,606; sh: 22,815; ansic: 18,277; python: 767; makefile: 99; perl: 20
file content (649 lines) | stat: -rw-r--r-- 23,069 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
#  Phusion Passenger - https://www.phusionpassenger.com/
#  Copyright (c) 2010-2014 Phusion
#
#  "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui.
#
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.

ORIG_TARBALL_FILES = lambda { PhusionPassenger::Packaging.files }

def recursive_copy_files(files, destination_dir, preprocess = false, variables = {})
	require 'fileutils' if !defined?(FileUtils)
	if !STDOUT.tty?
		puts "Copying files..."
	end
	files.each_with_index do |filename, i|
		dir = File.dirname(filename)
		if !File.exist?("#{destination_dir}/#{dir}")
			FileUtils.mkdir_p("#{destination_dir}/#{dir}")
		end
		if !File.directory?(filename)
			if preprocess && filename =~ /\.template$/
				real_filename = filename.sub(/\.template$/, '')
				FileUtils.install(filename, "#{destination_dir}/#{real_filename}", :preserve => true)
				Preprocessor.new.start(filename, "#{destination_dir}/#{real_filename}",
					variables)
			else
				FileUtils.install(filename, "#{destination_dir}/#{filename}", :preserve => true)
			end
		end
		if STDOUT.tty?
			printf "\r[%5d/%5d] [%3.0f%%] Copying files...", i + 1, files.size, i * 100.0 / files.size
			STDOUT.flush
		end
	end
	if STDOUT.tty?
		printf "\r[%5d/%5d] [%3.0f%%] Copying files...\n", files.size, files.size, 100
	end
end

def word_wrap(text, max = 72)
	while index = (lines = text.split("\n")).find_index{ |line| line.size > max }
		line = lines[index]
		pos = max
		while pos >= 0 && line[pos..pos] != " "
			pos -= 1
		end
		if pos < 0
			raise "Cannot wrap line: #{line}"
		else
			lines[index] = line[0 .. pos - 1]
			lines.insert(index + 1, line[pos + 1 .. -1])
			text = lines.join("\n")
		end
	end
	return text
end

def is_open_source?
	return !is_enterprise?
end

def is_enterprise?
	return PACKAGE_NAME =~ /enterprise/
end

def enterprise_git_url
	return "TODO"
end

def git_tag_prefix
	if is_open_source?
		return "release"
	else
		return "enterprise"
	end
end

def git_tag
	return "#{git_tag_prefix}-#{VERSION_STRING}"
end

def homebrew_dir
	return "/tmp/homebrew"
end


task :clobber => 'package:clean'

task 'package:set_official' do
	ENV['OFFICIAL_RELEASE'] = '1'
	# These environment variables interfere with 'brew install'
	# and maybe other stuff, so unset them.
	ENV.delete('CC')
	ENV.delete('CXX')
	ENV.delete('USE_CCACHE')
end

desc "Build, sign & upload gem & tarball"
task 'package:release' => ['package:set_official', 'package:gem', 'package:tarball', 'package:sign'] do
	PhusionPassenger.require_passenger_lib 'platform_info'
	require 'yaml'
	require 'uri'
	require 'net/http'
	require 'net/https'
	basename   = "#{PhusionPassenger::PACKAGE_NAME}-#{PhusionPassenger::VERSION_STRING}"
	version    = PhusionPassenger::VERSION_STRING
	is_beta        = !!version.split('.')[3]

	if !`git status --porcelain | grep -Ev '^\\?\\? '`.empty?
		STDERR.puts "-------------------"
		abort "*** ERROR: There are uncommitted files. See 'git status'"
	end

	begin
		website_config = YAML.load_file(File.expand_path("~/.passenger_website.yml"))
	rescue Errno::ENOENT
		STDERR.puts "-------------------"
		abort "*** ERROR: Please put the Phusion Passenger website admin " +
			"password in ~/.passenger_website.yml:\n" +
			"admin_password: ..."
	end

	if !PhusionPassenger::PlatformInfo.find_command("hub")
		STDERR.puts "-------------------"
		abort "*** ERROR: Please 'brew install hub' first"
	end

	if is_open_source?
		if boolean_option('HOMEBREW_UPDATE', true)
			puts "Updating Homebrew formula..."
			Rake::Task['package:update_homebrew'].invoke
		else
			puts "HOMEBREW_UPDATE set to false, not updating Homebrew formula."
		end
	end

	sh "git tag -s #{git_tag} -u 0A212A8C -m 'Release #{version}'"

	puts "Proceed with pushing tag to remote Git repo and uploading the gem and signatures? [y/n]"
	if STDIN.readline == "y\n"
		sh "git push origin #{git_tag}"

		if is_open_source?
			sh "s3cmd -P put #{PKG_DIR}/passenger-#{version}.{gem,tar.gz,gem.asc,tar.gz.asc} s3://phusion-passenger/releases/"
			sh "gem push #{PKG_DIR}/passenger-#{version}.gem"

			puts "Updating version number on website..."
			if is_beta
				uri = URI.parse("https://www.phusionpassenger.com/latest_beta_version")
			else
				uri = URI.parse("https://www.phusionpassenger.com/latest_stable_version")
			end
			http = Net::HTTP.new(uri.host, uri.port)
			http.use_ssl = true
			http.verify_mode = OpenSSL::SSL::VERIFY_PEER
			request = Net::HTTP::Post.new(uri.request_uri)
			request.basic_auth("admin", website_config["admin_password"])
			request.set_form_data("version" => version)
			response = http.request(request)
			if response.code != 200 && response.body != "ok"
				abort "*** ERROR: Cannot update version number on www.phusionpassenger.com:\n" +
					"Status: #{response.code}\n\n" +
					response.body
			end

			puts "Initiating building of binaries"
			Rake::Task['package:initiate_binaries_building'].invoke

			puts "Initiating building of Debian packages"
			Rake::Task['package:initiate_debian_building'].invoke

			puts "Building OS X binaries..."
			Rake::Task['package:build_osx_binaries'].invoke

			if boolean_option('HOMEBREW_UPDATE', true)
				if boolean_option('HOMEBREW_DRY_RUN', false)
					puts "HOMEBREW_DRY_RUN set, not submitting pull request. Please find the repo in /tmp/homebrew."
				else
					puts "Submitting Homebrew pull request..."
					sh "cd #{homebrew_dir} && hub pull-request 'Update passenger to version #{version}' -b Homebrew:master"
				end
			end

			puts "--------------"
			puts "All done."
		else
			dir = "/u/apps/passenger_website/shared"
			subdir = string_option('NAME', version)

			sh "scp #{PKG_DIR}/#{basename}.{gem,tar.gz,gem.asc,tar.gz.asc} app@shell.phusion.nl:#{dir}/"
			sh "ssh app@shell.phusion.nl 'mkdir -p \"#{dir}/assets/#{subdir}\" && mv #{dir}/#{basename}.{gem,tar.gz,gem.asc,tar.gz.asc} \"#{dir}/assets/#{subdir}/\"'"
			command = "curl -F file=@#{PKG_DIR}/#{basename}.gem --user admin:#{website_config['admin_password']} " +
				"--output /dev/stderr --write-out '%{http_code}' --silent " +
				"https://www.phusionpassenger.com/enterprise_gems/upload"
			puts command
			result = `#{command}`
			if result != "200"
				abort "Gem upload failed. HTTP status code: #{result.inspect}"
			else
				# The response body does not contain a newline,
				# so fix terminal output.
				puts
			end

			puts "Initiating building of binaries"
			Rake::Task['package:initiate_binaries_building'].invoke

			puts "Initiating building of Debian packages"
			Rake::Task['package:initiate_debian_building'].invoke

			puts "Building OS X binaries..."
			Rake::Task['package:build_osx_binaries'].invoke

			puts "--------------"
			puts "All done."
		end
	else
		puts "Did not upload anything."
	end
end

task 'package:gem' => Packaging::PREGENERATED_FILES do
	require 'phusion_passenger'
	if ENV['OFFICIAL_RELEASE']
		release_file = "#{PhusionPassenger.resources_dir}/release.txt"
		File.unlink(release_file) rescue nil
	end
	begin
		if release_file
			File.open(release_file, "w").close
		end
		command = "gem build #{PhusionPassenger::PACKAGE_NAME}.gemspec"
		if !boolean_option('SKIP_SIGNING')
			command << " --sign --key 0x0A212A8C"
		end
		sh(command)
	ensure
		if release_file
			File.unlink(release_file) rescue nil
		end
	end
	sh "mkdir -p #{PKG_DIR}"
	sh "mv #{PhusionPassenger::PACKAGE_NAME}-#{PhusionPassenger::VERSION_STRING}.gem #{PKG_DIR}/"
end

task 'package:tarball' => Packaging::PREGENERATED_FILES do
	require 'phusion_passenger'
	require 'fileutils'

	basename = "#{PhusionPassenger::PACKAGE_NAME}-#{PhusionPassenger::VERSION_STRING}"
	sh "rm -rf #{PKG_DIR}/#{basename}"
	sh "mkdir -p #{PKG_DIR}/#{basename}"
	recursive_copy_files(ORIG_TARBALL_FILES.call, "#{PKG_DIR}/#{basename}")
	if ENV['OFFICIAL_RELEASE']
		File.open("#{PKG_DIR}/#{basename}/resources/release.txt", "w").close
	end
	if PlatformInfo.os_name == "macosx"
		sh "cd #{PKG_DIR}/#{basename} && find . -print0 | xargs -0 touch -t '201310270000'"
	else
		sh "cd #{PKG_DIR}/#{basename} && find . -print0 | xargs -0 touch -d '2013-10-27 00:00:00 UTC'"
	end
	sh "cd #{PKG_DIR} && tar -c #{basename} | gzip --no-name --best > #{basename}.tar.gz"
	sh "rm -rf #{PKG_DIR}/#{basename}"
end

task 'package:sign' do
	if File.exist?(File.expand_path("~/.gnupg/gpg-agent.conf")) || ENV['GPG_AGENT_INFO']
		puts "It looks like you're using gpg-agent, so skipping automatically password caching."
	else
		begin
			require 'highline'
		rescue LoadError
			abort "Please run `gem install highline` first."
		end
		h = HighLine.new
		password = h.ask("Password for software-signing@phusion.nl GPG key: ") { |q| q.echo = false }
		passphrase_opt = "--passphrase-file .gpg-password"
	end

	begin
		if password
			File.open(".gpg-password", "w", 0600) do |f|
				f.write(password)
			end
		end
		version = PhusionPassenger::VERSION_STRING
		["passenger-#{version}.gem",
		 "passenger-#{version}.tar.gz",
		 "passenger-enterprise-server-#{version}.gem",
		 "passenger-enterprise-server-#{version}.tar.gz"].each do |name|
			if File.exist?("pkg/#{name}")
				sh "gpg --sign --detach-sign #{passphrase_opt} --local-user software-signing@phusion.nl --armor pkg/#{name}"
			end
		end
	ensure
		File.unlink('.gpg-password') if File.exist?('.gpg-password')
	end
end

task 'package:update_homebrew' do
	require 'digest/sha1'
	version = VERSION_STRING
	sha1 = File.open("#{PKG_DIR}/passenger-#{version}.tar.gz", "rb") do |f|
		Digest::SHA1.hexdigest(f.read)
	end
	sh "rm -rf #{homebrew_dir}"
	sh "git clone git@github.com:phusion/homebrew.git #{homebrew_dir}"
	sh "cd #{homebrew_dir} && git remote add Homebrew https://github.com/Homebrew/homebrew.git"
	sh "cd #{homebrew_dir} && git fetch Homebrew"
	sh "cd #{homebrew_dir} && git reset --hard Homebrew/master"
	formula = File.read("/tmp/homebrew/Library/Formula/passenger.rb")
	formula.gsub!(/passenger-.+?\.tar\.gz/, "passenger-#{version}.tar.gz") ||
		abort("Unable to substitute Homebrew formula tarball filename")
	formula.gsub!(/^  sha1 .*/, "  sha1 '#{sha1}'") ||
		abort("Unable to substitute Homebrew formula SHA-1")
	necessary_dirs = ORIG_TARBALL_FILES.call.map{ |filename| filename.split("/").first }.uniq
	necessary_dirs -= Packaging::HOMEBREW_EXCLUDE
	necessary_dirs += ["buildout"]
	necessary_dirs_str = word_wrap(necessary_dirs.inspect).split("\n").join("\n      ")
	formula.sub!(/necessary_files = .*?\]/m, "necessary_files = Dir#{necessary_dirs_str}") ||
		abort("Unable to substitute file whitelist")
	File.open("/tmp/homebrew/Library/Formula/passenger.rb", "w") do |f|
		f.write(formula)
	end
	sh "cd #{homebrew_dir} && git commit -a -m 'passenger #{version}'"
	sh "cd #{homebrew_dir} && git push -f"
	if boolean_option('HOMEBREW_TEST', true)
		sh "cp /tmp/homebrew/Library/Formula/passenger.rb /usr/local/Library/Formula/passenger.rb"
		if `brew info passenger` !~ /^Not installed$/
			sh "brew uninstall passenger"
		end
		sh "cp #{PKG_DIR}/passenger-#{version}.tar.gz `brew --cache`/"
		sh "brew install passenger"
		Rake::Task['test:integration:native_packaging'].invoke
	end
end

task 'package:initiate_binaries_building' do
	require 'yaml'
	require 'uri'
	require 'net/http'
	require 'net/https'
	version = VERSION_STRING
	begin
		website_config = YAML.load_file(File.expand_path("~/.passenger_website.yml"))
	rescue Errno::ENOENT
		STDERR.puts "-------------------"
		abort "*** ERROR: Please put the Phusion Passenger website admin " +
			"password in ~/.passenger_website.yml:\n" +
			"admin_password: ..."
	end
	if is_open_source?
		type = "open%20source"
		jenkins_token = website_config["jenkins_token"]
		if !jenkins_token
			abort "*** ERROR: Please put the Passenger open source Jenkins " +
				"authentication token in ~/.passenger_website.yml, under " +
				"the 'jenkins_token' key."
		end
	else
		type = "Enterprise"
		jenkins_token = website_config["jenkins_enterprise_token"]
		if !jenkins_token
			abort "*** ERROR: Please put the Passenger Enterprise Jenkins " +
				"authentication token in ~/.passenger_website.yml, under " +
				"the 'jenkins_enterprise_token' key."
		end
	end

	uri = URI.parse("https://oss-jenkins.phusion.nl/buildByToken/buildWithParameters?" +
		"job=Passenger%20#{type}%20binaries%20(release)&token=#{jenkins_token}&tag=#{git_tag}")
	http = Net::HTTP.new(uri.host, uri.port)
	http.use_ssl = true
	http.verify_mode = OpenSSL::SSL::VERIFY_PEER
	request = Net::HTTP::Post.new(uri.request_uri)
	response = http.request(request)
	if response.code != 200 && response.body != "Scheduled.\n"
		abort "*** ERROR: Cannot initiate building of binaries:\n" +
			"Status: #{response.code}\n\n" +
			response.body
	end
	puts "Initiated building of binaries."
end

task 'package:initiate_debian_building' do
	require 'yaml'
	require 'uri'
	require 'net/http'
	require 'net/https'
	version = VERSION_STRING
	begin
		website_config = YAML.load_file(File.expand_path("~/.passenger_website.yml"))
	rescue Errno::ENOENT
		STDERR.puts "-------------------"
		abort "*** ERROR: Please put the Phusion Passenger website admin " +
			"password in ~/.passenger_website.yml:\n" +
			"admin_password: ..."
	end
	if is_open_source?
		type = "open%20source"
		jenkins_token = website_config["jenkins_token"]
		if !jenkins_token
			abort "*** ERROR: Please put the Passenger open source Jenkins " +
				"authentication token in ~/.passenger_website.yml, under " +
				"the 'jenkins_token' key."
		end
	else
		type = "Enterprise"
		jenkins_token = website_config["jenkins_enterprise_token"]
		if !jenkins_token
			abort "*** ERROR: Please put the Passenger Enterprise Jenkins " +
				"authentication token in ~/.passenger_website.yml, under " +
				"the 'jenkins_enterprise_token' key."
		end
	end

	uri = URI.parse("https://oss-jenkins.phusion.nl/buildByToken/buildWithParameters?" +
		"job=Passenger%20#{type}%20Debian%20packages%20(release)&token=#{jenkins_token}&ref=#{git_tag}")
	http = Net::HTTP.new(uri.host, uri.port)
	http.use_ssl = true
	http.verify_mode = OpenSSL::SSL::VERIFY_PEER
	request = Net::HTTP::Post.new(uri.request_uri)
	response = http.request(request)
	if response.code != 200 && response.body != "Scheduled.\n"
		abort "*** ERROR: Cannot initiate building of Debian packages:\n" +
			"Status: #{response.code}\n\n" +
			response.body
	end
	puts "Initiated building of Debian packages."
end

task 'package:build_osx_binaries' do
	if is_open_source?
		sh "cd ../passenger_autobuilder && " +
			"git pull && " +
			"./autobuild-osx https://github.com/phusion/passenger.git passenger " +
				"psg_autobuilder_chroot@juvia-helper.phusion.nl --tag=#{git_tag}"
	else
		sh "cd ../passenger_autobuilder && " +
			"git pull && " +
			"./autobuild-osx #{enterprise_git_url} passenger-enterprise " +
			"psg_autobuilder_chroot@juvia-helper.phusion.nl --tag=#{git_tag}"
	end
end

desc "Remove gem, tarball and signatures"
task 'package:clean' do
	require 'phusion_passenger'
	basename = "#{PhusionPassenger::PACKAGE_NAME}-#{PhusionPassenger::VERSION_STRING}"
	sh "rm -f pkg/#{basename}.{gem,gem.asc,tar.gz,tar.gz.asc}"
end

def change_shebang(filename, value)
	contents = File.open(filename, "r") do |f|
		f.read
	end
	contents.gsub!(/\A#\!.+$/, "#!#{value}")
	File.open(filename, "w") do |f|
		f.write(contents)
	end
end

desc "Create a fakeroot, useful for building native packages"
task :fakeroot => [:apache2, :nginx, :doc] do
	require 'rbconfig'
	require 'fileutils'
	include RbConfig

	fs_prefix  = ENV['FS_PREFIX']  || "/usr"
	fs_bindir  = ENV['FS_BINDIR']  || "#{fs_prefix}/bin"
	fs_sbindir = ENV['FS_SBINDIR'] || "#{fs_prefix}/sbin"
	fs_datadir = ENV['FS_DATADIR'] || "#{fs_prefix}/share"
	fs_docdir  = ENV['FS_DOCDIR']  || "#{fs_datadir}/doc"
	fs_libdir  = ENV['FS_LIBDIR']  || "#{fs_prefix}/lib"

	# We don't use CONFIG['archdir'] and the like because we want
	# the files to be installed to /usr, and the Ruby interpreter
	# on the packaging machine might be in /usr/local.
	psg_rubylibdir = ENV['RUBYLIBDIR'] || CONFIG['vendordir'].sub(/^\/usr/,fs_prefix)
	psg_nodelibdir = "#{fs_datadir}/#{GLOBAL_NAMESPACE_DIRNAME}/node"
	psg_libdir     = "#{fs_libdir}/#{GLOBAL_NAMESPACE_DIRNAME}"
	psg_native_support_dir = ENV["RUBYARCHDIR"] || CONFIG['vendorarchdir'].sub(/^\/usr/,fs_prefix)
	psg_agents_dir = "#{fs_libdir}/#{GLOBAL_NAMESPACE_DIRNAME}/agents"
	psg_helper_scripts_dir = "#{fs_datadir}/#{GLOBAL_NAMESPACE_DIRNAME}/helper-scripts"
	psg_resources_dir      = "#{fs_datadir}/#{GLOBAL_NAMESPACE_DIRNAME}"
	psg_include_dir        = "#{fs_datadir}/#{GLOBAL_NAMESPACE_DIRNAME}/include"
	psg_docdir     = "#{fs_docdir}/#{GLOBAL_NAMESPACE_DIRNAME}"
	psg_bindir     = "#{fs_bindir}"
	psg_sbindir    = "#{fs_sbindir}"
	psg_apache2_module_path       = ENV['APACHE2_MODULE_PATH'] || "#{fs_libdir}/apache2/modules/mod_passenger.so"
	psg_ruby_extension_source_dir = "#{fs_datadir}/#{GLOBAL_NAMESPACE_DIRNAME}/ruby_extension_source"
	psg_nginx_module_source_dir   = "#{fs_datadir}/#{GLOBAL_NAMESPACE_DIRNAME}/ngx_http_passenger_module"

	fakeroot = "pkg/fakeroot"
	fake_rubylibdir = "#{fakeroot}#{psg_rubylibdir}"
	fake_nodelibdir = "#{fakeroot}#{psg_nodelibdir}"
	fake_libdir     = "#{fakeroot}#{psg_libdir}"
	fake_native_support_dir = "#{fakeroot}#{psg_native_support_dir}"
	fake_agents_dir = "#{fakeroot}#{psg_agents_dir}"
	fake_helper_scripts_dir = "#{fakeroot}#{psg_helper_scripts_dir}"
	fake_resources_dir = "#{fakeroot}#{psg_resources_dir}"
	fake_include_dir   = "#{fakeroot}#{psg_include_dir}"
	fake_docdir     = "#{fakeroot}#{psg_docdir}"
	fake_bindir     = "#{fakeroot}#{psg_bindir}"
	fake_sbindir    = "#{fakeroot}#{psg_sbindir}"
	fake_apache2_module_path       = "#{fakeroot}#{psg_apache2_module_path}"
	fake_ruby_extension_source_dir = "#{fakeroot}#{psg_ruby_extension_source_dir}"
	fake_nginx_module_source_dir   = "#{fakeroot}#{psg_nginx_module_source_dir}"

	native_packaging_method = ENV['NATIVE_PACKAGING_METHOD'] || "deb"

	sh "rm -rf #{fakeroot}"
	sh "mkdir -p #{fakeroot}"

	# Ruby sources
	sh "mkdir -p #{fake_rubylibdir}"
	sh "cp #{PhusionPassenger.ruby_libdir}/phusion_passenger.rb #{fake_rubylibdir}/"
	sh "cp -R #{PhusionPassenger.ruby_libdir}/phusion_passenger #{fake_rubylibdir}/"

	# Node.js sources
	sh "mkdir -p #{fake_nodelibdir}"
	sh "cp -R #{PhusionPassenger.node_libdir}/phusion_passenger #{fake_nodelibdir}/"

	# Phusion Passenger common libraries
	sh "mkdir -p #{fake_libdir}"
	sh "cp -R #{PhusionPassenger.lib_dir}/common #{fake_libdir}/"
	sh "rm -rf #{fake_libdir}/common/libboost_oxt"

	# Ruby extension binaries
	sh "mkdir -p #{fake_native_support_dir}"
	native_support_archdir = PlatformInfo.ruby_extension_binary_compatibility_id
	sh "mkdir -p #{fake_native_support_dir}"
	sh "cp -R buildout/ruby/#{native_support_archdir}/*.#{LIBEXT} #{fake_native_support_dir}/"

	# Agents
	sh "mkdir -p #{fake_agents_dir}"
	sh "cp -R #{PhusionPassenger.agents_dir}/* #{fake_agents_dir}/"
	sh "rm -rf #{fake_agents_dir}/*.dSYM"
	sh "rm -rf #{fake_agents_dir}/*/*.dSYM"
	sh "rm -rf #{fake_agents_dir}/*.o"

	# Helper scripts
	sh "mkdir -p #{fake_helper_scripts_dir}"
	sh "cp -R #{PhusionPassenger.helper_scripts_dir}/* #{fake_helper_scripts_dir}/"

	# Resources
	sh "mkdir -p #{fake_resources_dir}"
	sh "cp -R resources/* #{fake_resources_dir}/"

	# Headers necessary for building the Nginx module
	sh "mkdir -p #{fake_include_dir}"
	# Infer headers that the Nginx module needs
	headers = [
		["ext/common/Exceptions.h", "common/Exceptions.h"]
	]
	Dir["ext/nginx/*.[ch]"].each do |filename|
		File.read(filename).split("\n").grep(%r{#include "common/(.+)"}) do |match|
			headers << ["ext/common/#{$1}", "common/#{$1}"]
		end
	end
	headers.each do |header|
		target = "#{fake_include_dir}/#{header[1]}"
		dir = File.dirname(target)
		if !File.directory?(dir)
			sh "mkdir -p #{dir}"
		end
		sh "cp #{header[0]} #{target}"
	end

	# Nginx module sources
	sh "mkdir -p #{fake_nginx_module_source_dir}"
	sh "cp ext/nginx/* #{fake_nginx_module_source_dir}/"

	# Documentation
	sh "mkdir -p #{fake_docdir}"
	sh "cp doc/*.html #{fake_docdir}/"
	sh "cp -R doc/images #{fake_docdir}/"

	# User binaries
	sh "mkdir -p #{fake_bindir}"
	Packaging::USER_EXECUTABLES.each do |exe|
		sh "cp bin/#{exe} #{fake_bindir}/"
		if !Packaging::EXECUTABLES_WITH_FREE_RUBY.include?(exe)
			change_shebang("#{fake_bindir}/#{exe}", "#{fs_bindir}/ruby")
		end
	end

	# Superuser binaries
	sh "mkdir -p #{fake_sbindir}"
	Packaging::SUPER_USER_EXECUTABLES.each do |exe|
		sh "cp bin/#{exe} #{fake_sbindir}/"
		if !Packaging::EXECUTABLES_WITH_FREE_RUBY.include?(exe)
			change_shebang("#{fake_sbindir}/#{exe}", "#{fs_bindir}/ruby")
		end
	end

	# Apache 2 module
	sh "mkdir -p #{File.dirname(fake_apache2_module_path)}"
	sh "cp #{APACHE2_MODULE} #{fake_apache2_module_path}"

	# Ruby extension sources
	sh "mkdir -p #{fake_ruby_extension_source_dir}"
	sh "cp -R #{PhusionPassenger.ruby_extension_source_dir}/* #{fake_ruby_extension_source_dir}"

	puts "Creating #{fake_rubylibdir}/phusion_passenger/locations.ini"
	File.open("#{fake_rubylibdir}/phusion_passenger/locations.ini", "w") do |f|
		f.puts "[locations]"
		f.puts "natively_packaged=true"
		f.puts "native_packaging_method=#{native_packaging_method}"
		f.puts "bin_dir=#{psg_bindir}"
		f.puts "agents_dir=#{psg_agents_dir}"
		f.puts "lib_dir=#{psg_libdir}"
		f.puts "helper_scripts_dir=#{psg_helper_scripts_dir}"
		f.puts "resources_dir=#{psg_resources_dir}"
		f.puts "include_dir=#{psg_include_dir}"
		f.puts "doc_dir=#{psg_docdir}"
		f.puts "ruby_libdir=#{psg_rubylibdir}"
		f.puts "node_libdir=#{psg_nodelibdir}"
		f.puts "apache2_module_path=#{psg_apache2_module_path}"
		f.puts "ruby_extension_source_dir=#{psg_ruby_extension_source_dir}"
		f.puts "nginx_module_source_dir=#{psg_nginx_module_source_dir}"
	end

	# Sanity check the locations.ini file
	options = PhusionPassenger.parse_ini_file("#{fake_rubylibdir}/phusion_passenger/locations.ini")
	PhusionPassenger::REQUIRED_LOCATIONS_INI_FIELDS.each do |field|
		if !options[field.to_s]
			raise "Bug in build/packaging.rb: the generated locations.ini is missing the '#{field}' field"
		end
	end

	sh "find #{fakeroot} -name .DS_Store -print0 | xargs -0 rm -f"
end