#!/usr/bin/env ruby

# Exit codes:
# 0   Test run successful (even with reruns)
# 1   Unspecified error
# 2   Linting failed
# 4   No profile given
# 8   Gettext isn't installed
# 16  Gettext files did not validate
# 32  Cucumber failed
# 64  Rspec failed

# TODO: Use Open4 to continuously flush STDOUT output from the cucumber
# processes.

require 'rubygems'
require 'fileutils'
require 'pry'
require 'open4'

PROFILES = ['default']

def die(exit_code, error)
  puts "Error: #{error}"
  exit exit_code
end

def run_command(cmd)
  pid, stdin, stdout, _stderr = Open4.open4("#{cmd} 2>&1")
  stdin.close
  puts stdout.read 1024 until stdout.eof?
  Process.waitpid2(pid).last.exitstatus
end

def gettext_installed?
  `which msgcat >> /dev/null`
  if $CHILD_STATUS.exitstatus == 0
    return true
  else
    return false
  end
end

def gettext_file_valid?(file)
  `msgcat #{file} >> /dev/null`
  if $CHILD_STATUS.exitstatus == 0
    return true
  else
    return false
  end
end

def gettext_files_valid?
  files = ['locale/vinylla.pot']
  files += Dir.glob('locale/**/leihs.po')
  files.each do |file|
    return false unless gettext_file_valid?(file)
  end
  true
end

def rerun_cucumber(maximum = 3, run_count = 0)
  return true if run_count >= maximum
  if File.exist?('tmp/rererun.txt')
    FileUtils.mv('tmp/rererun.txt', 'tmp/rerun.txt')
  end
  return false unless File.exist?('tmp/rerun.txt') && File.size('tmp/rerun.txt') > 0
  puts 'Rerun necessary.'
  exitstatus = run_command('bundle exec cucumber -p rerun')
  run_count += 1
  if exitstatus != 0
    rerun_cucumber(maximum, run_count)
  else
    die(0, 'All went well after rerunning.')
  end
end

# Do we know what we're doing?

profile = ARGV[0]
if PROFILES.include?(profile) == false
  die(4, "Please specify a valid profile, one of #{PROFILES.join(', ')}.")
end

# 1. Prerequisites for testing

# We're not actually using gettext yet in Vinylla and it's undecided
# whether we will.
# if not gettext_installed?
#   die(8, "Gettext isn't installed. Make sure you have gettext and \
#     msgcat and msgmerge are in your PATH.")
# end

# if not gettext_files_valid?
#   die(16, 'The gettext files did not validate.')
# end

# 2. Linting
exitstatus = run_command('bundle exec rubocop --lint')
die(2, 'Rubocop is disgusted. Clean up that filthy code!') if exitstatus != 0

# 3. Testing proper
exitstatus = run_command('bundle exec rspec')
die(64, 'Rspec failed') if exitstatus != 0

# puts 'Prerequisites for running the tests are met'
# puts 'Starting Cucumber...'
# FileUtils.rm_f(['tmp/rerun.txt', 'tmp/rererun.txt'])
# exitstatus = run_command("bundle exec cucumber -p #{profile}")

# Rerun for failures, up to n times
# if exitstatus != 0
#   rerun(4)
# else
#   die(0, 'All went well on the very first run. The planets must be in alignment.')
# end
