#!/usr/bin/env oo-ruby
#--
# Copyright 2010 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 'rubygems'
require 'openshift-origin-node'
require 'open4'
require 'shellwords'

def usage
  puts <<USAGE
== Synopsis

#{$0}: Executes a connector on a cartridge component
  This command must be run as root.

== Usage

#{$0} GEAR_UUID CART_NAME HOOK_NAME <args-to-connector>

Options:
-h|--help:
   Prints this message

GEAR_UUID: Unique identifier for gear that the component is running on
CART_NAME: Unique identifier for the cartridge that the component belongs to
HOOK_NAME: Name of the connector to be executed

USAGE
  exit 255
end

opts = GetoptLong.new(
    ['--gear-uuid',       '-g', GetoptLong::REQUIRED_ARGUMENT],
    ['--cart-name',       '-c', GetoptLong::REQUIRED_ARGUMENT],
    ['--hook-name',       '-h', GetoptLong::REQUIRED_ARGUMENT],
    ['--porcelain',           '-q', GetoptLong::NO_ARGUMENT],
    ['--debug',               '-d', GetoptLong::NO_ARGUMENT],
    ['--help',                '-?', GetoptLong::NO_ARGUMENT]
)

args = {}
begin
  opts.each{ |k,v| args[k]=v }
rescue GetoptLong::Error => e
  usage
end

if args["--help"]
  usage
end

gear_uuid = args['--gear-uuid']
cart_name = args['--cart-name']
hook_name = args['--hook-name']
$oo_debug = true if args['--debug']
$porcelain = args['--porcelain'] ? true : false

config = OpenShift::Config.instance
unless gear_uuid
  usage
end

exitcode = 0
begin
  cart_dir = config.get('CARTRIDGE_BASE_PATH')
  if File.exists? "#{cart_dir}/#{cart_name}/info/connection-hooks/#{hook_name}"                
     shellsafe_argv = ARGV.map { |arg| Shellwords::shellescape(arg) }
     pid, stdin, stdout, stderr = Open4::popen4ext(true,
        "#{cart_dir}/#{cart_name}/info/connection-hooks/#{hook_name} #{shellsafe_argv.join(' ')} 2>&1")
     ignored, status = Process::waitpid2 pid
     exitcode = status.exitstatus
     zout = stdout.gets
     zout = "" if zout.nil?
     $stdout.puts zout
  end
rescue Exception => e
  $stderr.puts(e.message)
  exit -1
end
exit exitcode
