#!/usr/bin/env ruby
#
# Copyright 2011-2013, Dell
# Copyright 2013-2014, SUSE LINUX Products GmbH
#
# 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 'rubygems'
require 'json'
require 'getoptlong'

MAGIC_DOT = '@@ESCAPED_DOT@@'

#
# Parsing options can be added by adding to this list before calling opt_parse
#
@options = [
    [ [ '--help', '-h', GetoptLong::NO_ARGUMENT ], "--help or -h - help" ],
    [ [ '--attribute', '-a', GetoptLong::REQUIRED_ARGUMENT ], "--attribute <attribute> or -a <attribute>  - Name of hash object to return.  Use . as sub-hash delimiter" ]
]

@attributes = []


def usage (rc)
  puts "Usage: json-read [options] [filename]"
  @options.each do |options|
    puts "  #{options[1]}"
  end
  exit rc
end

def help
  usage 0
end


### Start MAIN ###

def opt_parse()
  sub_options = @options.map { |x| x[0] }
  lsub_options = @options.map { |x| [ x[0][0], x[2] ] }
  opts = GetoptLong.new(*sub_options)

  opts.each do |opt, arg|
    case opt
      when '--help'
        usage 0
      when '--attribute'
        @attributes << arg
      else
        usage -1
    end
  end

  if ARGV.length > 1
    usage -1
  end
end

def main()
  opt_parse

  begin
    if (ARGV.length == 1)
      file = File.open(ARGV[0])
    else
      file = STDIN
    end
    hash = JSON.parse(file.read)

    @attributes.each do |attr|
      data = hash
      # Protect already escaped periods from being interpreted as
      # element delimiters.  Notice that the 1st parameter to gsub is
      # a String not a Regexp.
      fields = attr.gsub('\.', MAGIC_DOT).split('.')
      fields.each { |x| data = data[x.gsub(MAGIC_DOT, '.')] unless data.nil? }

      if data.is_a? Hash
        puts "#{attr}=#{data.to_json}"
      else
        puts "#{attr}=#{data}"
      end
    end
  rescue => ex
    puts "json-read failed: #{ex.message}"
    ex.backtrace.each { |bt_line| puts "#{bt_line}" }
    exit -1
  end

end

main

