#!/usr/local/bin/perl
# 
# $Header: opsm/utl/ghappctl.pl /main/1 2011/11/16 22:35:24 sowong Exp $
#
# ghappctl.pl
# 
# Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. 
#
#    NAME
#      ghappctl.pl - Grid Home Application Check Action Phase 2
#
#    DESCRIPTION
#     This script sends a request to the default web application. The http port
#     is passed as a parameter
#     This is a 2 level HTTP listener check
#     1. Check if the OC4J container is up/down
#     2. Check if Grid Home application running in the container is up/down.
#
#    NOTES
#     Grid Home Application Check Action Modelling
#     Container=UP, GH=UP   => STATE=ONLINE (Resource is o.k.)
#     Container=UP, GH=DOWN => STATE=FAILED (Resource Cleaned/Restarted by CRS)
#     Container=DOWN        => STATE=FAILED(Resource Restarted by CRS)
#
#    MODIFIED   (MM/DD/YY)
#    sowong      10/31/11 - Creation
# 
use strict;
use LWP;

# HTTP State Code
my $http_failed = 5;
my $http_online = 0;
my $http_port;
my $urlContainer;
my $urlGH;
my $ua;
my $req;
my $response;
my $req_method = "GET";
my $action;

# Read the default http port passed as 2nd argument to script
# The first argument is the action to be performed (currently unused)
$action = $ARGV[0];
$http_port = $ARGV[1];

$urlContainer = "http://localhost:" . $http_port . "/";
$urlGH = "http://localhost:" . $http_port . "/gridhome-root/gridhome";

# create a browser
$ua = LWP::UserAgent->new();

# Create request  object for this URL

# Ping the Container, send request and get response
$req = HTTP::Request->new($req_method, $urlContainer);
$response = $ua->request($req);

# Check response
if ($response->is_success)
{
   # Dump ret from successful container ping
   print STDOUT "$urlContainer: ", $response, "\n";
   print STDOUT "Retcode (Container): ", $response->code, "\n";

   # Now ping GH
   $req = HTTP::Request->new($req_method, $urlGH);
   $response = $ua->request($req);
   if ($response->is_success)
   {
      # Returning resource state=ONLINE to agent
      print STDOUT "$urlGH: ", $response, "\n";
      print STDOUT "Retcode (GH): ", $response->code, "\n";
      exit $http_online;
   }
   else
   {
      # Returning resource state=FAILED to agent
      print STDERR "$0: Could not fetch $urlGH\n";
      print STDOUT "Retcode (GH): ", $response->code, "\n";
      exit $http_failed;
   }
}
else
{
      # Returning resource state=FAILED to agent
      print STDERR "$0: Could not fetch $urlContainer\n";
      print STDOUT "Retcode (Container): ", $response->code, "\n";
      exit $http_failed;
}
