#!/usr/bin/env oo-ruby
#--
# Copyright 2013 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.
#++

def usage
  $stderr.puts <<USAGE
== Synopsis

#{$0}: Issue command to all cartridges in a gear
  This command must be run as the unix user

== Usage

#{$0} [--with-container-uuid 1c3a5f7a92e111e188d800262df50034] \\
            --action start

== List of arguments
       -a|--action                           One of <start|stop|build|deploy|restart|reload|restore|snapshot>
       -c|--with-container-uuid   gear_uuid  Unique identifier for the gear (default: running user)
       -d|--debug                            enable additional output
       -h|--help                             Print this message
USAGE
  exit 255
end

require "rubygems"
require 'openshift-origin-node'
require 'openshift-origin-node/utils/environ'
require 'openshift-origin-node/utils/path_utils'
require "etc"

opts = GetoptLong.new(
    ['--action', '-a', GetoptLong::REQUIRED_ARGUMENT],
    ['--with-container-uuid', '-c', GetoptLong::REQUIRED_ARGUMENT],
    ['--help', '-h', GetoptLong::NO_ARGUMENT],
)

uuid   = Etc.getlogin
action = nil
opts.each do |opt, arg|
  case opt
    when '--help'
      usage
    when '--with-container-uuid'
      uuid = arg
    when '--action'
      action = arg if %w(start stop restart reload restore snapshot).include? arg
    when '--debug'
      $DEBUG = true
  end
end

unless action && uuid && 0 == ARGV.length
  $stderr.puts "Invalid arguments\n"
  usage
end


begin
  passwd    = Etc.getpwnam(uuid)
  stop_lock = PathUtils.join(passwd.dir, %w{app-root runtime .stop_lock})

  case action
    when 'stop'
      FileUtils.touch stop_lock
    when 'start'
      FileUtils.remove stop_lock
    else
      if File.exist? stop_lock
        env = Utils::Environ.for_gear(passwd.homedir)
        $stderr.puts "Application is explicitly stopped!  Use 'rhc app start -a #{env['OPENSHIFT_APP_NAME']} to start back up."
      end
  end

  container = OpenShift::ApplicationContainer.new(uuid, uuid)
  container.send action.to_sym
rescue OpenShift::Utils::ShellExecutionException => e
  $stderr.puts "#{e.message}: rc(#{e.rc})"

  if $DEBUG
    $stderr.puts "stdout: #{e.stdout}\nstderr#{e.stderr}"
    $stderr.puts e.backtrace.join("\n")
  end

  exit -1
rescue Exception => e
  $stderr.puts e.message
  exit -1
else
  exit 0
end
