File: passenger-install-apache2-module

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 (861 lines) | stat: -rwxr-xr-x 28,892 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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
#!/usr/bin/env ruby
# encoding: binary
#  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.

## Magic comment: begin bootstrap ##
require 'phusion_passenger'
## Magic comment: end bootstrap ##

PhusionPassenger.locate_directories

# The Apache executable may be located in an 'sbin' folder. We add
# the 'sbin' folders to $PATH just in case. On some systems
# 'sbin' isn't in $PATH unless the user is logged in as root from
# the start (i.e. not via 'su' or 'sudo').
ENV["PATH"] += ":/usr/sbin:/sbin:/usr/local/sbin"

require 'optparse'
require 'stringio'
PhusionPassenger.require_passenger_lib 'constants'
PhusionPassenger.require_passenger_lib 'platform_info/ruby'
PhusionPassenger.require_passenger_lib 'platform_info/apache'
PhusionPassenger.require_passenger_lib 'platform_info/apache_detector'
PhusionPassenger.require_passenger_lib 'abstract_installer'
PhusionPassenger.require_passenger_lib 'utils/terminal_choice_menu'

class Installer < PhusionPassenger::AbstractInstaller
	include PhusionPassenger
	TerminalChoiceMenu = PhusionPassenger::Utils::TerminalChoiceMenu

	AUTOINSTALL_BEGIN_LOAD_BLOCK = "### Begin automatically installed #{PROGRAM_NAME} load snippet ###"
	AUTOINSTALL_END_LOAD_BLOCK   = "### End automatically installed #{PROGRAM_NAME} load snippet ###"
	AUTOINSTALL_BEGIN_CONF_BLOCK = "### Begin automatically installed #{PROGRAM_NAME} config snippet ###"
	AUTOINSTALL_END_CONF_BLOCK   = "### End automatically installed #{PROGRAM_NAME} config snippet ###"

	def dependencies
		specs = [
			'depcheck_specs/compiler_toolchain',
			'depcheck_specs/ruby',
			'depcheck_specs/gems',
			'depcheck_specs/libs',
			'depcheck_specs/apache2'
		]
		ids = [
			'cc',
			'c++',
			'libcurl-dev',
			'openssl-dev',
			'zlib-dev',
			'apache2',
			'apache2-dev',
			'rake',
			'ruby-openssl',
			'rubygems'
		]
		if @languages.include?("ruby")
			if PlatformInfo.passenger_needs_ruby_dev_header?
				ids << 'ruby-dev'
			end
			ids << 'rack'
		end
		# Some broken servers don't have apr-config or apu-config installed.
		# Nevertheless, it is possible to compile Apache modules if Apache
		# was configured with --included-apr. So here we check whether
		# apr-config and apu-config are available. If they're not available,
		# then we only register them as required dependency if no Apache
		# module can be compiled without their presence.
		if (PlatformInfo.apr_config && PlatformInfo.apu_config) ||
		   PlatformInfo.apr_config_needed_for_building_apache_modules?
			ids << 'apr-dev'
			ids << 'apu-dev'
		end
		return [specs, ids]
	end
	
	def users_guide_path
		return PhusionPassenger.apache2_doc_path
	end

	def users_guide_url
		return APACHE2_DOC_URL
	end
	
	def run_steps
		if PhusionPassenger.natively_packaged? && PhusionPassenger.apache2_module_source_dir.nil?
			if apache_module_available?
				notify_apache_module_installed
				show_deployment_example
			else
				install_apache_module_from_native_package || exit(1)
			end
			exit
		end
		
		Dir.chdir(PhusionPassenger.apache2_module_source_dir)
		show_welcome_screen
		query_interested_languages
		check_gem_install_permission_problems || exit(1)
		check_directory_accessible_by_web_server
		check_dependencies || exit(1)
		check_whether_there_are_multiple_apache_installs || exit
		check_whether_apache_uses_compatible_mpm
		check_whether_os_is_broken
		check_whether_system_has_enough_ram
		check_write_permission_to_passenger_root || exit(1)
		check_write_permission_to_web_server_config_files || exit(1)
		if compile_apache2_module
			install_apache2_config_snippets || exit(1)
			show_deployment_example
		else
			show_possible_solutions_for_compilation_and_installation_problems
			exit(1)
		end
	end

private
	def show_welcome_screen
		render_template 'apache2/welcome', :version => VERSION_STRING
		wait
	end

	def query_interested_languages
		menu = TerminalChoiceMenu.new(["Ruby", "Python", "Node.js", "Meteor"])
		menu["Ruby"].checked = interesting_language?('ruby')
		menu["Python"].checked = interesting_language?('python')
		menu["Node.js"].checked = interesting_language?('nodejs', 'node')
		menu["Meteor"].checked = interesting_language?('meteor')

		new_screen
		puts "<banner>Which languages are you interested in?</banner>"
		puts
		if interactive?
			puts "Use <space> to select."
			puts "<dgray>If the menu doesn't display correctly, press '!'</dgray>"
		else
			puts "Override selection with --languages."
		end
		puts

		if interactive?
			begin
				menu.query
			rescue Interrupt
				raise Abort
			end
		else
			menu.display_choices
			puts
		end

		@languages = menu.selected_choices.map{ |x| x.downcase.gsub(/\./, '') }
	end

	def interesting_language?(name, command = nil)
		if @languages
			return @languages.include?(name)
		else
			return !!PlatformInfo.find_command(command || name)
		end
	end

	def check_whether_there_are_multiple_apache_installs
		new_screen
		puts '<banner>Sanity checking Apache installation...</banner>'

		output = StringIO.new
		detector = PlatformInfo::ApacheDetector.new(output)
		begin
			detector.detect_all
			detector.report
			@apache2 = detector.result_for(PlatformInfo.apxs2)
			if @apache2.nil?
				render_template 'apache2/apache_install_broken',
					:apxs2 => PlatformInfo.apxs2,
					:sudo_s_e => PhusionPassenger::PlatformInfo.ruby_sudo_shell_command("-E"),
					:ruby => PhusionPassenger::PlatformInfo.ruby_command,
					:passenger_config => "#{PhusionPassenger.bin_dir}/passenger-config"
				return false
			end
			if detector.results.size > 1
				other_installs = detector.results - [@apache2]
				render_template 'apache2/multiple_apache_installations_detected',
					:current => @apache2,
					:other_installs => other_installs
				puts
				if interactive?
					result = prompt_confirmation "Are you sure you want to install " +
						"against Apache #{@apache2.version} (#{@apache2.apxs2})?"
					if !result
						puts
						line
						render_template 'apache2/installing_against_a_different_apache',
							:other_installs => other_installs
					end
					return result
				else
					puts '<yellow>Continuing installation because --auto is given.</yellow>'
					return true
				end
			else
				puts '<green>All good!</green>'
				return true
			end
		ensure
			detector.finish
		end
	end
	
	def check_whether_apache_uses_compatible_mpm
		# 'httpd -V' output is in the form of:
		#
		# Server MPM:      Prefork     # <--- this line is not always available!
		# ...
		# Server compiled with....
		#  -D APACHE_MPM_DIR="server/mpm/prefork"
		output = PlatformInfo.httpd_V
		output =~ /^Server MPM: +(.*)$/
		if $1
			mpm = $1.downcase
		else
			output =~ /APACHE_MPM_DIR="server\/mpm\/(.*)"/
			if $1
				mpm = $1.downcase
			else
				mpm = nil
			end
		end
		if mpm != "prefork" && mpm != "worker" && mpm != "event"
			new_screen
			render_template 'apache2/apache_must_be_compiled_with_compatible_mpm',
				:current_mpm => mpm
			wait
		end
	end
	
	def check_write_permission_to_passenger_root
		File.new("__test__.txt", "w").close
		return true
	rescue SystemCallError
		puts
		line
		if Process.uid == 0
			render_template 'installer_common/cannot_access_files_as_root',
				:type => "directory",
				:files => [PhusionPassenger.apache2_module_source_dir]
		else
			render_template 'installer_common/run_installer_as_root',
				:dir  => PhusionPassenger.apache2_module_source_dir,
				:sudo => PhusionPassenger::PlatformInfo.ruby_sudo_command,
				:sudo_s_e => PhusionPassenger::PlatformInfo.ruby_sudo_shell_command("-E"),
				:ruby => PhusionPassenger::PlatformInfo.ruby_command,
				:installer => "#{PhusionPassenger.bin_dir}/passenger-install-apache2-module #{ORIG_ARGV.join(' ')}"
		end
		return false
	ensure
		File.unlink("__test__.txt") rescue nil
	end

	def check_write_permission_to_web_server_config_files
		return true if !@update_config
		config_file = PlatformInfo.httpd_default_config_file
		return if !config_file || !File.exist?(config_file)

		all_config_files = PlatformInfo.httpd_included_config_files(config_file)
		if all_config_files[:unreadable_files].any?
			puts
			line
			if Process.uid == 0
				render_template 'installer_common/cannot_access_files_as_root',
					:access => "read from",
					:files => all_config_files[:unreadable_files]
			else
				render_template 'installer_common/run_installer_as_root',
					:access => "read from",
					:desc => "an Apache configuration file",
					:sudo => PhusionPassenger::PlatformInfo.ruby_sudo_command,
					:sudo_s_e => PhusionPassenger::PlatformInfo.ruby_sudo_shell_command("-E"),
					:ruby => PhusionPassenger::PlatformInfo.ruby_command,
					:installer => "#{PhusionPassenger.bin_dir}/passenger-install-apache2-module #{ORIG_ARGV.join(' ')}"
			end
			puts
			render_template 'apache2/present_choice_for_no_update_config'
			return false
		end

		unwriteable_files = []
		all_config_files[:files].each do |filename|
			if !File.writable_real?(filename)
				unwriteable_files << filename
			end
		end
		if unwriteable_files.empty?
			return true
		else
			puts
			line
			if Process.uid == 0
				render_template 'installer_common/cannot_access_files_as_root',
					:files => unwriteable_files
			else
				render_template 'installer_common/run_installer_as_root',
					:desc => "an Apache configuration file",
					:sudo => PhusionPassenger::PlatformInfo.ruby_sudo_command,
					:sudo_s_e => PhusionPassenger::PlatformInfo.ruby_sudo_shell_command("-E"),
					:ruby => PhusionPassenger::PlatformInfo.ruby_command,
					:installer => "#{PhusionPassenger.bin_dir}/passenger-install-apache2-module #{ORIG_ARGV.join(' ')}"
			end
			puts
			render_template 'apache2/present_choice_for_no_update_config'
			return false
		end
	end
	
	def compile_apache2_module
		puts
		line
		puts '<banner>Compiling and installing Apache 2 module...</banner>'
		if @compile
			puts "cd #{PhusionPassenger.apache2_module_source_dir}"
			if ENV['TRACE']
				rake = "#{PlatformInfo.rake_command} --trace RELEASE=yes"
			else
				rake = "#{PlatformInfo.rake_command} RELEASE=yes"
			end
			command = "#{rake} apache2:clean apache2"
			if PhusionPassenger.native_packaging_method == "homebrew"
				# Running apache2:clean deletes some object files needed
				# by passenger-install-nginx-module, so we ensure those
				# object files are compiled.
				command << " nginx"
			end
			return sh(command)
		else
			puts "Skipping compilation"
			return true
		end
	end
	
	def load_snippet
		return "LoadModule passenger_module #{PhusionPassenger.apache2_module_path}"
	end

	def config_snippet
		return "<IfModule mod_passenger.c>\n" +
			"  PassengerRoot #{PhusionPassenger.source_root}\n" +
			"  PassengerDefaultRuby #{PlatformInfo.ruby_command}\n" +
			"</IfModule>"
	end

	def apache2_config_snippets
		return "#{load_snippet}\n#{config_snippet}\n"
	end

	def backup_config_files(config_file, all_config_files)
		now = Time.now.strftime("%Y-%m-%d-%H:%M:%S")
		archive = "#{config_file}.#{GLOBAL_NAMESPACE_DIRNAME}-backup-#{now}.tar.gz"
		backup_files = all_config_files.dup

		# Some people create a regular file in /etc/apache2/mods-enabled, for convenience
		# reasons. This file is not actually managed by a2enmod. We will remove such files
		# because we're going to use mods-eanbled ourselves, so we need to back them up.
		if (dir = PlatformInfo.httpd_mods_enabled_directory) && PlatformInfo.a2enmod
			if File.file?("#{dir}/#{APACHE2_MODULE_CONF_NAME}.load")
				backup_files << "#{dir}/#{APACHE2_MODULE_CONF_NAME}.load"
			end
			if File.file?("#{dir}/#{APACHE2_MODULE_CONF_NAME}.conf")
				backup_files << "#{dir}/#{APACHE2_MODULE_CONF_NAME}.conf"
			end
		end

		puts "Backing up existing configuration files to #{archive}..."
		backup_files.uniq!
		backup_files.map! { |x| x.sub(/^\//, '') }
		Dir.chdir("/") do
			sh! "tar", "-czf", archive, *backup_files
		end
	end

	def uninstall_or_comment_out_existing_config_snippets(all_config_files)
		files_containing_autoinstall_load_blocks = []
		files_containing_autoinstall_conf_blocks = []

		# Some people create a regular file in /etc/apache2/mods-enabled, for convenience
		# reasons. This file is not actually managed by a2enmod. We remove such files
		# because we're going to use mods-enabled ourselves. They've already been backed up.
		if (dir = PlatformInfo.httpd_mods_enabled_directory) && PlatformInfo.a2enmod
			filename = "#{dir}/#{APACHE2_MODULE_CONF_NAME}.load"
			if File.file?(filename) && !File.symlink?(filename)
				puts "Removing #{filename}"
				File.unlink(filename)
			end
			filename = "#{dir}/#{APACHE2_MODULE_CONF_NAME}.conf"
			if File.file?(filename) && !File.symlink?(filename)
				puts "Removing #{filename}"
				File.unlink(filename)
			end
		end

		# Uncomment Phusion Passenger config snippets.
		all_config_files.each do |filename|
			next if !File.exist?(filename)

			contents = File.open(filename, "rb") do |f|
				f.read
			end
			if contents =~ /#{Regexp.escape AUTOINSTALL_BEGIN_LOAD_BLOCK}.*?#{Regexp.escape AUTOINSTALL_END_LOAD_BLOCK}/m
				files_containing_autoinstall_load_blocks << filename
			end
			if contents =~ /#{Regexp.escape AUTOINSTALL_BEGIN_CONF_BLOCK}.*?#{Regexp.escape AUTOINSTALL_END_CONF_BLOCK}/m
				files_containing_autoinstall_conf_blocks << filename
			end
			subst1 = contents.gsub!(/^([ \t]*LoadModule[ \t]+passenger_module[ \t]+.*)$/i, '# \1')
			subst2 = contents.gsub!(/^([ \t]*PassengerRoot[ \t]+.*)$/i, '# \1')
			subst3 = contents.gsub!(/^([ \t]*PassengerDefaultRuby[ \t]+.*)$/i, '# \1')
			if subst1 || subst2 || subst3
				puts "Uninstalling previous #{PROGRAM_NAME} from #{filename}..."
				File.open(filename, "wb") do |f|
					f.write(contents)
				end
			end
		end

		# If there are multiple auto-install comment blocks, remove the duplicates.
		# First, we remove all comment blocks from all files besides the first one.
		if files_containing_autoinstall_load_blocks.size > 1
			files_containing_autoinstall_load_blocks[1..-1].each do |filename|
				puts "Removing duplicate load snippets from #{filename}..."
				remove_comment_blocks(filename,
					AUTOINSTALL_BEGIN_LOAD_BLOCK,
					AUTOINSTALL_END_LOAD_BLOCK)
			end
		end
		if files_containing_autoinstall_conf_blocks.size > 1
			files_containing_autoinstall_conf_blocks[1..-1].each do |filename|
				puts "Removing duplicate conf snippets from #{filename}..."
				remove_comment_blocks(filename,
					AUTOINSTALL_BEGIN_CONF_BLOCK,
					AUTOINSTALL_END_CONF_BLOCK)
			end
		end

		# Then we are left with exactly 0 or exactly 1 file with comment blocks
		# of each type. There may be duplicates inside that single file, so
		# remove duplicates there too.
		if files_containing_autoinstall_load_blocks.size > 0
			filename = files_containing_autoinstall_load_blocks[0]
			puts "Removing duplicate load snippets inside #{filename}..."
			remove_duplicate_comment_blocks(filename,
				AUTOINSTALL_BEGIN_LOAD_BLOCK,
				AUTOINSTALL_END_LOAD_BLOCK)
		end
		if files_containing_autoinstall_conf_blocks.size > 0
			filename = files_containing_autoinstall_conf_blocks[0]
			puts "Removing duplicate configuration snippets inside #{filename}..."
			remove_duplicate_comment_blocks(filename,
				AUTOINSTALL_BEGIN_CONF_BLOCK,
				AUTOINSTALL_END_CONF_BLOCK)
		end

		# One or more files may have been removed, so filter out the ones
		# that are left.
		all_config_files.reject! do |filename|
			!File.exist?(filename)
		end
	end

	def remove_comment_blocks(filename, begin_marker, end_marker)
		contents = File.open(filename, "rb") do |f|
			f.read
		end
		regexp = /#{Regexp.escape begin_marker}.*?#{Regexp.escape end_marker}\n?/m
		contents.gsub!(regexp, '')
		File.open(filename, "wb") do |f|
			f.write(contents)
		end
	end

	def remove_duplicate_comment_blocks(filename, begin_marker, end_marker)
		contents = File.open(filename, "rb") do |f|
			f.read
		end
		regexp = /#{Regexp.escape begin_marker}.*?#{Regexp.escape end_marker}\n?/m
		if m = regexp.match(contents)
			offset = m.end(0)
			rest = contents.slice!(m.end(0) .. -1)
			rest.gsub!(regexp, '')
			contents << rest
			File.open(filename, "wb") do |f|
				f.write(contents)
			end
		end
	end

	def add_new_config_snippets(all_config_files)
		# Look for the file containing the auto-install load and conf comment blocks.
		# The uninstall_or_comment_out_existing_config_snippets method has already
		# guaranteed that there is at most 1 file per comment block type, and that
		# inside each file there are no duplicate comment blocks.
		load_block_file = find_config_file_containing_comment_block(all_config_files,
			AUTOINSTALL_BEGIN_LOAD_BLOCK,
			AUTOINSTALL_END_LOAD_BLOCK)
		conf_block_file = find_config_file_containing_comment_block(all_config_files,
			AUTOINSTALL_BEGIN_CONF_BLOCK,
			AUTOINSTALL_END_CONF_BLOCK)
		if load_block_file && conf_block_file
			puts "Updating #{PROGRAM_NAME} module load snippet inside #{load_block_file}..."
			update_comment_block(load_block_file,
				AUTOINSTALL_BEGIN_LOAD_BLOCK,
				AUTOINSTALL_END_LOAD_BLOCK,
				load_snippet)
			puts "Updating #{PROGRAM_NAME} configuration snippet inside #{conf_block_file}..."
			update_comment_block(conf_block_file,
				AUTOINSTALL_BEGIN_CONF_BLOCK,
				AUTOINSTALL_END_CONF_BLOCK,
				config_snippet)
		elsif !load_block_file && !conf_block_file
			create_load_snippet_file(:maybe_in_mods_available)
			create_conf_snippet_file(:maybe_in_mods_available)
			if PlatformInfo.httpd_mods_available_directory && PlatformInfo.a2enmod
				sh! "#{PlatformInfo.a2enmod} #{APACHE2_MODULE_CONF_NAME}"
			end
		# It looks like either the load or conf file isn't available.
		# If the file that is available is inside mods-available, then it
		# means that the mods-available files are broken.
		elsif is_file_inside_mods_available?(load_block_file, "#{APACHE2_MODULE_CONF_NAME}.load") ||
		      is_file_inside_mods_available?(conf_block_file, "#{APACHE2_MODULE_CONF_NAME}.conf")
			# We fix it if a2enmod is available. Otherwise, we remove the block.
			if PlatformInfo.a2enmod
				if !load_block_file
					create_load_snippet_file(:must_be_in_mods_available)
				else
					create_conf_snippet_file(:must_be_in_mods_available)
				end
			else
				if load_block_file
					puts "Removing load snippets from #{filename}..."
					remove_comment_blocks(load_block_file,
						AUTOINSTALL_BEGIN_LOAD_BLOCK,
						AUTOINSTALL_END_LOAD_BLOCK)
				else
					puts "Removing configuration snippets from #{filename}..."
					remove_comment_blocks(conf_block_file,
						AUTOINSTALL_BEGIN_CONF_BLOCK,
						AUTOINSTALL_END_CONF_BLOCK)
				end
				create_load_snippet_file(:must_be_in_mods_available)
				create_conf_snippet_file(:must_be_in_mods_available)
			end
			sh! "#{PlatformInfo.a2enmod} passenger"
		else
			if !load_block_file
				create_load_snippet_file(:not_in_mods_available)
				puts "Updating #{PROGRAM_NAME} configuration snippet inside #{conf_block_file}..."
				update_comment_block(conf_block_file,
					AUTOINSTALL_BEGIN_CONF_BLOCK,
					AUTOINSTALL_END_CONF_BLOCK,
					config_snippet)
			else
				create_conf_snippet_file(:not_in_mods_available)
				puts "Updating #{PROGRAM_NAME} module load snippet inside #{load_block_file}..."
				update_comment_block(load_block_file,
					AUTOINSTALL_BEGIN_LOAD_BLOCK,
					AUTOINSTALL_END_LOAD_BLOCK,
					load_snippet)
			end
		end
	end

	def find_config_file_containing_comment_block(all_config_files, begin_marker, end_marker)
		regexp = /#{Regexp.escape begin_marker}.*?#{Regexp.escape end_marker}/m
		all_config_files.each do |filename|
			contents = File.open(filename, "rb") do |f|
				f.read
			end
			if contents =~ regexp
				return filename
			end
		end
		return nil
	end

	def update_comment_block(filename, begin_marker, end_marker, block_contents)
		regexp = /#{Regexp.escape begin_marker}.*?#{Regexp.escape end_marker}\n?/m
		contents = File.open(filename, "rb") do |f|
			f.read
		end
		if contents.sub!(regexp, "#{begin_marker}\n#{block_contents}\n#{end_marker}\n")
			File.open(filename, "wb") do |f|
				f.write(contents)
			end
			return true
		else
			return false
		end
	end

	def remove_comment_blocks(filename, begin_marker, end_marker)
		regexp = /#{Regexp.escape begin_marker}.*?#{Regexp.escape end_marker}\n?/m
		contents = File.open(filename, "rb") do |f|
			f.read
		end
		contents.gsub!(regexp, "")
		File.open(filename, "wb") do |f|
			f.write(contents)
		end
	end

	def is_file_inside_mods_available?(filename, basename)
		if dir = PlatformInfo.httpd_mods_available_directory
			return filename == "#{dir}/#{basename}"
		else
			return false
		end
	end

	def create_load_snippet_file(where)
		case where
		when :maybe_in_mods_available
			if PlatformInfo.httpd_mods_available_directory && PlatformInfo.a2enmod
				filename = "#{PlatformInfo.httpd_mods_available_directory}/#{APACHE2_MODULE_CONF_NAME}.load"
			else
				filename = PlatformInfo.httpd_default_config_file
			end
		when :must_be_in_mods_available
			if PlatformInfo.httpd_mods_available_directory && PlatformInfo.a2enmod
				filename = "#{PlatformInfo.httpd_mods_available_directory}/#{APACHE2_MODULE_CONF_NAME}.load"
			else
				raise "Apache does not support the mods-available directory"
			end
		when :not_in_mods_available
			filename = PlatformInfo.httpd_default_config_file
		else
			raise ArgumentError
		end

		if File.exist?(filename)
			# If this is a file inside mods-available, and the file didn't have a symlink
			# in mods-enabled, then the uninstall phase did not remove duplicates from this
			# file. So here we remove duplicates again.
			puts "Removing duplicate load snippets inside #{filename}..."
			remove_duplicate_comment_blocks(filename,
				AUTOINSTALL_BEGIN_LOAD_BLOCK,
				AUTOINSTALL_END_LOAD_BLOCK)

			puts "Installing #{PROGRAM_NAME} module load snippet to #{filename}..."
			should_add = !update_comment_block(filename,
				AUTOINSTALL_BEGIN_LOAD_BLOCK,
				AUTOINSTALL_END_LOAD_BLOCK,
				load_snippet)
		else
			puts "Installing #{PROGRAM_NAME} module load snippet to #{filename}..."
			should_add = true
		end
		if should_add
			File.open(filename, "ab") do |f|
				f.write("\n#{AUTOINSTALL_BEGIN_LOAD_BLOCK}\n" +
					"#{load_snippet}\n" +
					"#{AUTOINSTALL_END_LOAD_BLOCK}\n")
			end
		end
	end

	def create_conf_snippet_file(where)
		case where
		when :maybe_in_mods_available
			if PlatformInfo.httpd_mods_available_directory && PlatformInfo.a2enmod
				filename = "#{PlatformInfo.httpd_mods_available_directory}/#{APACHE2_MODULE_CONF_NAME}.conf"
			else
				filename = PlatformInfo.httpd_default_config_file
			end
		when :must_be_in_mods_available
			if PlatformInfo.httpd_mods_available_directory && PlatformInfo.a2enmod
				filename = "#{PlatformInfo.httpd_mods_available_directory}/#{APACHE2_MODULE_CONF_NAME}.conf"
			else
				raise "Apache does not support the mods-available directory"
			end
		when :not_in_mods_available
			filename = PlatformInfo.httpd_default_config_file
		else
			raise ArgumentError
		end

		if File.exist?(filename)
			# If this is a file inside mods-available, and the file didn't have a symlink
			# in mods-enabled, then the uninstall phase did not remove duplicates from this
			# file. So here we remove duplicates again.
			puts "Removing duplicate configuration snippets inside #{filename}..."
			remove_duplicate_comment_blocks(filename,
				AUTOINSTALL_BEGIN_CONF_BLOCK,
				AUTOINSTALL_END_CONF_BLOCK)

			puts "Installing #{PROGRAM_NAME} module configuration snippet to #{filename}..."
			should_add = !update_comment_block(filename,
				AUTOINSTALL_BEGIN_CONF_BLOCK,
				AUTOINSTALL_END_CONF_BLOCK,
				config_snippet)
		else
			puts "Installing #{PROGRAM_NAME} module configuration snippet to #{filename}..."
			should_add = true
		end
		if should_add
			File.open(filename, "ab") do |f|
				f.write("\n#{AUTOINSTALL_BEGIN_CONF_BLOCK}\n" +
					"#{config_snippet}\n" +
					"#{AUTOINSTALL_END_CONF_BLOCK}\n")
			end
		end
	end

	def install_apache2_config_snippets
		if !@update_config
			show_apache2_config_snippets
			return true
		end

		config_file = PlatformInfo.httpd_default_config_file
		if config_file && File.exist?(config_file)
			puts
			line
			puts "<banner>Updating Apache configuration files...</banner>"
			config_file = PlatformInfo.httpd_default_config_file
			all_config_files = PlatformInfo.httpd_included_config_files(config_file)[:files]
			backup_config_files(config_file, all_config_files) if @backup_config
			uninstall_or_comment_out_existing_config_snippets(all_config_files)
			add_new_config_snippets(all_config_files)
			return true
		else
			show_apache2_config_snippets
			return true
		end
	end

	def show_apache2_config_snippets
		puts
		line
		render_template 'apache2/config_snippets',
			:snippet => apache2_config_snippets
		wait
	end

	def show_deployment_example
		new_screen
		render_template 'apache2/deployment_example',
			:users_guide_path => users_guide_path,
			:users_guide_url => users_guide_url,
			:phusion_website => PHUSION_WEBSITE,
			:passenger_website => PASSENGER_WEBSITE,
			:languages => @languages
	end
	
	def show_possible_solutions_for_compilation_and_installation_problems
		new_screen
		render_template 'apache2/possible_solutions_for_compilation_and_installation_problems',
			:users_guide_path => users_guide_path,
			:users_guide_url => users_guide_url,
			:support_url => SUPPORT_URL
	end

	def apache_module_available?
		return File.exist?(PhusionPassenger.apache2_module_path)
	end

	def install_apache_module_from_native_package
		case PhusionPassenger.native_packaging_method
		when 'deb'
			sh! "sudo apt-get update"
			sh! "sudo apt-get install #{DEB_APACHE_MODULE_PACKAGE}"
			return true
		when 'rpm'
			sh! "sudo yum install #{RPM_APACHE_MODULE_PACKAGE}-#{VERSION_STRING}"
			return true
		else
			puts "<red>The #{PROGRAM_NAME} Apache module package is not installed.</red>"
			puts "Please ask your operating system vendor how to install it."
			return false
		end
	end

	def notify_apache_module_installed
		render_template 'apache2/notify_apache_module_installed'
		wait
	end
end

ORIG_ARGV = ARGV.dup
options = { :compile => true, :update_config => false, :backup_config => true }
parser = OptionParser.new do |opts|
	opts.banner = "Usage: passenger-install-apache2-module [options]"
	opts.separator ""
	
	indent = ' ' * 37
	opts.separator "Options:"
	opts.on("-a", "--auto", String, "Automatically build the Apache module,\n" <<
	        "#{indent}without interactively asking for user\n" <<
	        "#{indent}input.") do
		options[:auto] = true
	end
	opts.on("--apxs2-path PATH", String, "Path to 'apxs2' command.") do |value|
		ENV['APXS2'] = value
	end
	opts.on("--apr-config-path PATH", String, "Path to 'apr-config' command.") do |value|
		ENV['APR_CONFIG'] = value
	end
	opts.on("--languages NAMES", "Comma-separated list of interested\n" <<
			"#{indent}languages (e.g.\n" <<
			"#{indent}'ruby,python,nodejs,meteor')") do |value|
		options[:languages] = value.split(",")
	end
	opts.on("--no-compile", "Skip compilation.") do
		options[:compile] = false
	end
	#opts.on("--no-update-config", "Do not automatically update Apache config\n" <<
	#		"#{indent}files.") do
	#	options[:update_config] = false
	#end
	#opts.on("--no-backup-config", "When updating Apache config files, do not\n" <<
	#		"#{indent}create backups of the existing files.") do
	#	options[:backup_config] = false
	#end
	opts.on("--force-colors", "Display colors even if stdout is not a TTY") do
		options[:colorize] = true
	end
	opts.on("--snippet", "Show just the Apache config snippet.") do
		options[:snippet] = true
	end
end
begin
	parser.parse!
rescue OptionParser::ParseError => e
	puts e
	puts
	puts "Please see '--help' for valid options."
	exit 1
end

installer = Installer.new(options)
if options[:snippet]
	puts installer.send(:apache2_config_snippets)
else
	installer.run
end