#!/usr/bin/env ruby
# Copyright 2011 Red Hat, Inc.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

require 'rhc-common'

#
# print help
#
def p_usage
    rhlogin = get_var('default_rhlogin') ? "Default: #{get_var('default_rhlogin')}" : "required"
    puts <<USAGE

Usage: #{$0}
Display information about a user

  -l|--rhlogin   rhlogin    Red Hat login (RHN or OpenShift login with OpenShift Express access) (#{rhlogin})
  -p|--password  password   RHLogin password (optional, will prompt)
  -a|--apps                 List applications for rhlogin
  -i|--info                 Show user info
  -d|--debug                Print Debug info
  -h|--help                 Show Usage info
  --config  path            Path of alternate config file
  --timeout #               Timeout, in seconds, for connection

USAGE
exit 255
end

begin
    opts = GetoptLong.new(
        ["--debug", "-d", GetoptLong::NO_ARGUMENT],
        ["--help",  "-h", GetoptLong::NO_ARGUMENT],
        ["--apps",  "-a", GetoptLong::NO_ARGUMENT],
        ["--info",  "-i", GetoptLong::NO_ARGUMENT],
        ["--rhlogin",  "-l", GetoptLong::REQUIRED_ARGUMENT],
        ["--config", GetoptLong::REQUIRED_ARGUMENT],
        ["--password",  "-p", GetoptLong::REQUIRED_ARGUMENT],
        ["--timeout", GetoptLong::REQUIRED_ARGUMENT]
    )
    opt = {}
    opts.each do |o, a|
        opt[o[2..-1]] = a.to_s
    end
rescue Exception => e
  #puts e.message
    p_usage
end

# If provided a config path, check it
check_cpath(opt)

# Pull in configs from files
libra_server = get_var('libra_server')
debug = get_var('debug') == 'false' ? nil : get_var('debug')

if opt["help"]
    p_usage
end

if opt["debug"]
    debug = true
end
RHC::debug(debug)

RHC::timeout(opt["timeout"] ? opt["timeout"] : get_var('timeout'))

opt["rhlogin"] = get_var('default_rhlogin') unless opt["rhlogin"]

if !RHC::check_rhlogin(opt['rhlogin'])
    p_usage
end

password = opt['password']
if !password
  password = RHC::get_password
end

opt['apps'] = true if not opt['info'] and not opt['apps']
user_info = RHC::get_user_info(libra_server, opt['rhlogin'], password, @http, true)

if opt['info']
    ssh_keys = RHC::get_ssh_keys(libra_server, opt['rhlogin'], password, @http)

    puts "User Info"
    puts "========="
    puts "Namespace: #{user_info['user_info']['namespace']}"
    #puts "    UUID: #{user_info['user_info']['uuid']}"
    puts "  RHLogin: #{user_info['user_info']['rhlogin']}"
    puts "Primary SSH key: #{user_info['user_info']['ssh_key']}"
    puts "Primary SSH key type: #{user_info['user_info']['ssh_type']}"  unless user_info['user_info']['ssh_type'].to_s.strip.length == 0

    if ssh_keys && ssh_keys.kind_of?(Hash)
      puts ""
      puts "Additional SSH keys"
      puts "==================="
      ssh_keys.each do |name, keyval|
        puts "Name: #{name}"
        puts " Key: #{keyval['key']}"
        puts "Type: #{keyval['type']}"
        puts ""
      end
      puts "Use rhc-ctl-domain for managing additional ssh keys"
    end
    
end

if opt['apps']
    puts "\n\n" if opt['info']

    puts "Application Info"
    puts "================"
    unless user_info['app_info'].empty?
      user_info['app_info'].each do |key, val|
          puts key
          puts "    Framework: #{val['framework']}"
          puts "     Creation: #{val['creation_time']}"
          puts "         UUID: #{val['uuid']}"
          puts "      Git URL: ssh://#{val['uuid']}@#{key}-#{user_info['user_info']['namespace']}.#{user_info['user_info']['rhc_domain']}/~/git/#{key}.git/"
          puts "   Public URL: http://#{key}-#{user_info['user_info']['namespace']}.#{user_info['user_info']['rhc_domain']}/"
          if val['aliases'] && !val['aliases'].empty?
            puts "      Aliases: #{val['aliases'].join(', ')}"
          end
          puts ""
          puts " Embedded: "
          if val['embedded'] && !val['embedded'].empty? 
              val['embedded'].each do |embed_key, embed_val|
                  if embed_val.has_key?('info') && !embed_val['info'].empty?
                      puts "      #{embed_key} - #{embed_val['info']}"
                  else
                      puts "      #{embed_key}"
                  end
              end
          else
              puts "      None"
          end
          puts ""
      end
    else
      puts "No applications found.  You can use rhc-create-app to create new applications."
    end

end

exit 0