#!/usr/bin/ruby
#
# Ensure that some critical directories have expected-permissions.
#
# Expected in this context means `0755`.
#

#
# Allow access to our common-code.
#
$LOAD_PATH << '/usr/share/bytemark'
$LOAD_PATH << '../lib/bytemark' if ENV['TEST'] && ENV['TEST_PREFIX']

require 'healthcheck/command_output'

require 'yaml'

if __FILE__ == $PROGRAM_NAME

  def verbose(str)
    STDERR.puts(str)
  end

  to_raise = []
  failed = []

  #
  # Test these paths.
  #
  %w(/etc /bin /sbin /usr/bin /usr/sbin).each do |path|

    #
    # By invoking `stat`.
    #
    out = Bytemark::Healthcheck::CommandWrapper.run_command("stat --format=%a #{path}")
    out.split("\n").each do |line|
      failed << path unless line == '755' || line == '775'
    end
  end

  unless failed.empty?
    h = {}
    h[:id]      = 'insecure-path-low'
    h[:summary] = "#{failed.size} paths have non-standard permissions."
    h[:detail]  = "<p>The following directories have non-standard permissions: #{failed.join(',')}.</p>"
    to_raise.push(h)
  end

  # Show the output.
  puts YAML.dump(to_raise)
  exit(0)
end
