#!/usr/bin/env ruby

require 'rhc/coverage_helper'

require 'rhc-common'
require 'base64'

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

Usage: #{$0}
Tail the logs of an application

  -l|--rhlogin   rhlogin    OpenShift login (#{rhlogin})
  -a|--app                  Target application (required)
  -f|--files                File glob relative to app (default <application_name>/logs/*) (optional)
  -o|--opts                 Options to pass to the server-side (linux based) tail command (-f is implicit.  See the linux tail man page full list of options.) (Ex: --opts '-n 100')
  -p|--password  password   Password (optional, will prompt)
  -d|--debug                Print Debug info
  -h|--help                 Show Usage info
  --config  path            Path of alternate config file
  --timeout #               Timeout, in seconds, for the session

USAGE
exit exit_code
end

begin
    opts = GetoptLong.new(
        ["--debug", "-d", GetoptLong::NO_ARGUMENT],
        ["--help",  "-h", GetoptLong::NO_ARGUMENT],
        ["--app",  "-a", GetoptLong::REQUIRED_ARGUMENT],
        ["--opts",  "-o", GetoptLong::REQUIRED_ARGUMENT],
        ["--files",  "-f", GetoptLong::REQUIRED_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
RHC::Config.check_cpath(opt)

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

p_usage 0 if opt['help']

p_usage if !opt['app'] || 0 != ARGV.length

debug = true if opt['debug']

RHC::debug(debug)

RHC::timeout(opt["timeout"], get_var('timeout'))
RHC::connect_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

user_info = RHC::get_user_info(libra_server, opt['rhlogin'], password, RHC::Config.default_proxy, false)

app = opt['app']

unless user_info['app_info'][app]
    puts
    puts "Could not find app '#{opt['app']}'.  Please run rhc-domain-info to get a list"
    puts "of your current running applications"
    puts
    exit 101
end

opt['files'] = "*/log*/*" unless opt['files']
file_glob = "#{opt['files']}"
app_uuid = user_info['app_info'][app]['uuid']
namespace = user_info['user_info']['domains'][0]['namespace']
rhc_domain = user_info['user_info']['rhc_domain']

# -t to force PTY and avoid daemons
# Red Hat OpenShift: https://bugzilla.redhat.com/show_bug.cgi?id=726646
# OpenSSH https://bugzilla.mindrot.org/show_bug.cgi?id=396

remote_cmd = "tail#{opt['opts'] ? ' --opts ' + Base64::encode64(opt['opts']).chomp : ''} #{file_glob}"
ssh_cmd = "ssh -t #{app_uuid}@#{app}-#{namespace}.#{rhc_domain} '#{remote_cmd}'"

puts "Attempting to tail files: #{file_glob}"
puts "Use ctl + c to stop"
puts ssh_cmd if debug
begin
  if opt['files'] == 'system-messages'
     RHC::ctl_app(libra_server, RHC::Config.default_proxy, opt['app'], opt['rhlogin'], password,
                  'system-messages', false, nil, nil)
  else
     ssh_ruby("#{app}-#{namespace}.#{rhc_domain}", app_uuid, remote_cmd)
  end
rescue Interrupt
    puts
    puts "Terminating..."
    exit 0
rescue SocketError => e
  puts
  puts "Could not connect: #{e.message}"
  puts
  puts "DEBUG: #{e.debug}" if debug
  puts "You can try to run this manually if you have ssh installed: "
  puts
  puts ssh_cmd
  puts
  exit 1
end
# this should never happen
exit 1
