#!/usr/bin/ruby

#   Copyright 2011 Red Hat, Inc.
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

require "yaml"

filename = ARGV[0]
errors = []

if File.exist?(filename) == false
  puts "File not found: #{filename}"
  exit 1
else

  # file should be parseable
  begin
    YAML::parse_file(filename)
  rescue => e
    if e.to_s.index("line")
      line_number = e.to_s.split("line")[1].split(",")[0].strip.to_i + 1
      errors << "Incorrect format found on or before line #{line_number}"
    else
      errors << e
    end
  end

  # file should only have parameters and classes as top nodes
  if errors.size == 0
    begin
      root = YAML::load_file(filename)
      root.each do |key, value|
        if key != "parameters" && key != "classes"
          errors << "Please check formatting in line containing #{key} #{value}"
        end
      end
    rescue => e
      errors << e
    end
  end

  if errors.size > 0
    puts "Error found in #{filename}"
    errors.each do |e|
      puts e
    end
    puts "The config files are in YAML. Please use the following conventions: "
    puts "* Spaces and not tabs should be used to indent."
    puts "* A node must be indented further away from its parent node. We use 2 spaces."
    puts "* All sibling nodes must be indented with the same number of spaces. "
    puts "* The parameter name and value is separated by a colon and a space."
    exit 1
  end

end

exit 0
