/* $Id$ */
/*============================================================================*
 |                 Copyright (c) 2008 Applaud Solutions UK Ltd                |
 |                             All rights reserved                            |
 *===========================================================================*/

SET FEEDBACK OFF
SET VERIFY OFF
WHENEVER SQLERROR EXIT FAILURE ROLLBACK
WHENEVER OSERROR EXIT FAILURE ROLLBACK

DECLARE

  l_patch_name        varchar2(400) := '&1';
  l_patch_description varchar2(400) := '&2';
  l_bg_steps          varchar2(30)  := '&3';
  l_session_id		  number 		:= &4;
  l_node_name		  varchar2(31)	:= '&5';
  l_node_type		  varchar2(30)	:= '&6';
  l_appltop_id		  number		:= &7;
  l_autoconfig_status varchar2(1)	:= '&8';
  l_current_status	  varchar2(1)	:= '&9';
  l_num_started number;

  CURSOR csr_get_existing IS
  SELECT num_started 
  FROM   xxas_com_applied_patches ap
  WHERE  ap.patch_name = l_patch_name
  AND node_name=l_node_name
  AND session_id=l_session_id;

BEGIN

  --
  -- Determine if this patch is already registered
  --
  OPEN  csr_get_existing;
  FETCH csr_get_existing INTO l_num_started;
  CLOSE csr_get_existing;

  IF l_num_started IS NOT NULL THEN
    --
    -- Update the patch status
    --
    UPDATE xxas_com_applied_patches
    SET    current_status = 'S'
          ,num_started = l_num_started + 1
          ,last_update_date = sysdate
    WHERE  patch_name = l_patch_name
	AND node_name=l_node_name
	AND session_id=l_session_id;
  ELSE
    --
    -- Register the patch
    --
    INSERT INTO xxas_com_applied_patches
      (session_id
	  ,node_name
	  ,node_type
	  ,appltop_id
	  ,autoconfig_status
	  ,patch_name
      ,patch_description
      ,current_status
      ,bg_status
      ,num_started
      ,num_finished
      ,creation_date
      ,last_update_date)
    VALUES
      (l_session_id
	  ,l_node_name
	  ,l_node_type
	  ,l_appltop_id
	  ,l_autoconfig_status
	  ,l_patch_name
      ,l_patch_description
      ,l_current_status
      ,l_bg_steps
      ,1
      ,0
      ,sysdate
      ,sysdate);
  END IF;

END;
/
COMMIT;
EXIT;
