require 'open-uri'
require 'openssl'
require 'timeout'

require 'capybara'
require 'capybara/dsl'
require 'capybara/rspec'
require 'selenium-webdriver'

if ENV['FIREFOX']
	Capybara.register_driver :firefox do |app|
		options = Selenium::WebDriver::Firefox::Options.new(
			args: %w[--headless]
		)
		capabilities = Selenium::WebDriver::Remote::Capabilities.firefox(
			acceptInsecureCerts: true,
		)
		Capybara::Selenium::Driver.new(
			app,
			browser: :firefox,
			options: options,
			desired_capabilities: capabilities
		)
	end

	Capybara.configure do | config |
		config.default_driver = :firefox
		config.app_host = 'http://localhost'
		config.run_server = false
	end
else
	Capybara.register_driver :chrome do |app|
		options = Selenium::WebDriver::Chrome::Options.new(
			args: %w[headless disable-gpu no-sandbox ignore-certificate-errors]
		)
		Capybara::Selenium::Driver.new(app, browser: :chrome, options: options)
	end

	Capybara.configure do | config |
		config.default_driver = :chrome
		config.app_host = 'http://localhost'
		config.run_server = false
	end
end

# This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
  # rspec-expectations config goes here. You can use an alternate
  # assertion/expectation library such as wrong or the stdlib/minitest
  # assertions if you prefer.
  config.expect_with :rspec do |expectations|
    # This option will default to `true` in RSpec 4. It makes the `description`
    # and `failure_message` of custom matchers include text for helper methods
    # defined using `chain`, e.g.:
    #     be_bigger_than(2).and_smaller_than(4).description
    #     # => "be bigger than 2 and smaller than 4"
    # ...rather than:
    #     # => "be bigger than 2"
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  # rspec-mocks config goes here. You can use an alternate test double
  # library (such as bogus or mocha) by changing the `mock_with` option here.
  config.mock_with :rspec do |mocks|
    # Prevents you from mocking or stubbing a method that does not exist on
    # a real object. This is generally recommended, and will default to
    # `true` in RSpec 4.
    mocks.verify_partial_doubles = true
  end

  # This option will default to `:apply_to_host_groups` in RSpec 4 (and will
  # have no way to turn it off -- the option exists only for backwards
  # compatibility in RSpec 3). It causes shared context metadata to be
  # inherited by the metadata hash of host groups and examples, rather than
  # triggering implicit auto-inclusion in groups with matching metadata.
  config.shared_context_metadata_behavior = :apply_to_host_groups

# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
  # This allows you to limit a spec run to individual examples or groups
  # you care about by tagging them with `:focus` metadata. When nothing
  # is tagged with `:focus`, all examples get run. RSpec also provides
  # aliases for `it`, `describe`, and `context` that include `:focus`
  # metadata: `fit`, `fdescribe` and `fcontext`, respectively.
  config.filter_run_when_matching :focus

  # Allows RSpec to persist some state between runs in order to support
  # the `--only-failures` and `--next-failure` CLI options. We recommend
  # you configure your source control system to ignore this file.
  config.example_status_persistence_file_path = "spec/examples.txt"

  # Limits the available syntax to the non-monkey patched syntax that is
  # recommended. For more details, see:
  #   - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
  #   - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
  #   - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
  config.disable_monkey_patching!

  # This setting enables warnings. It's recommended, but in some cases may
  # be too noisy due to issues in dependencies.
  config.warnings = true

  # Many RSpec users commonly either run the entire suite or an individual
  # file, and it's useful to allow more verbose output when running an
  # individual spec file.
  if config.files_to_run.one?
    # Use the documentation formatter for detailed output,
    # unless a formatter has already been configured
    # (e.g. via a command-line flag).
    config.default_formatter = "doc"
  end

  # Print the 10 slowest examples and example groups at the
  # end of the spec run, to help surface which specs are running
  # particularly slow.
  config.profile_examples = 10

  # Run specs in random order to surface order dependencies. If you find an
  # order dependency and want to debug it, you can fix the order by providing
  # the seed, which is printed after each run.
  #     --seed 1234
  config.order = :random

  # Seed global randomization in this process using the `--seed` CLI option.
  # Setting this allows you to use `--seed` to deterministically reproduce
  # test failures related to randomization by passing the same `--seed` value
  # as the one that triggered the failure.
  Kernel.srand config.seed
=end

	config.include Capybara::DSL, :type => :feature

	config.before(:suite) do
		# Install the snap and create an admin user
		install_nextcloud

		# Ensure the first run wizard is disabled, just in case
		`sudo nextcloud.occ -n app:disable firstrunwizard`
	end

	config.after(:each) do
		# Chrome has an aggresive cache (including redirects). The easiest way to get
		# around it is to close it after each test
		Capybara.current_session.driver.quit

		# After each test, make sure maintenance mode is reset
		run 'sudo nextcloud.occ -n maintenance:mode --off 2>&1'

		# Maintenance mode takes two seconds to apply (opcache)
		sleep 3

		# Make sure any and all backups are removed
		`sudo rm -rf /var/snap/nextcloud/common/backups`

		# Make sure we're using the normal, HTTP host again
		Capybara.app_host = 'http://localhost'
	end

	def enable_https(port: nil)
		run 'sudo nextcloud.enable-https self-signed'
		wait_for_nextcloud(https: true, port: port)
	end

	def disable_https
		# Don't verify the output of this command: it will fail if
		# HTTPS wasn't enabled, which will be the case sometimes.
		`sudo nextcloud.disable-https`
		wait_for_nextcloud
	end

	def wait_for_nextcloud(https: false, port: nil)
		url = 'http://localhost'
		if https
			url = 'https://localhost'
		end

		uri = URI.parse(url)
		if port
			uri.port = port
		end

		wait_for("Timed out trying to access Nextcloud: #{uri.to_s}") do
			begin
				output = URI.open(uri, {ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE}).readlines.join('')
				next output.include? 'Nextcloud'
			rescue Errno::ECONNREFUSED
				# Do nothing: try again
			rescue OpenURI::HTTPError => error
				# Ignore 503s, wait for PHP to come up and try again
				if error.io.status[0] != '503'
					raise
				end
			end
			false
		end
	end

	def wait_for_maintenance_mode_to_be_off
		wait_for('Timed out waiting for maintenance mode to be off') do
			!nextcloud_is_in_maintenance_mode
		end
	end

	def wait_for_nextcloud_fixer
		wait_for('Timed out waiting for Nextcloud Fixer to finish') do
			!nextcloud_fixer_is_running
		end
	end

	def wait_for(failure_message)
		begin
			Timeout.timeout(30) do
				while !yield
					sleep 1
				end
			end
		rescue Timeout::Error
			fail failure_message
		end
	end

	def set_config(options)
		options_string = ""
		options.each do |key, value|
			options_string += "#{key}=#{value} "
		end

		run "sudo snap set nextcloud #{options_string}"
		run 'snap watch --last=configure-snap'
	end

	def nextcloud_is_installed
		`sudo snap run --shell nextcloud.occ -c '. "$SNAP/utilities/nextcloud-utilities" && nextcloud_is_installed'`
		$?.to_i == 0
	end

	def nextcloud_is_in_maintenance_mode
		`sudo snap run --shell nextcloud.occ -c '. "$SNAP/utilities/nextcloud-utilities" && nextcloud_is_in_maintenance_mode'`
		$?.to_i == 0
	end

	def nextcloud_fixer_is_running
		`snap services nextcloud.nextcloud-fixer | grep -qw active`
		$?.to_i == 0
	end

	def install_nextcloud
		unless nextcloud_is_installed
			run 'sudo nextcloud.manual-install admin admin'
		end
	end

	def run(command, expect_success: true)
		system(command)
		if expect_success
			expect($?.to_i).to eq 0
		else
			expect($?.to_i).not_to eq 0
		end
	end
end
