#include <stdio.h>
#include <string.h>
#include "sap_moni.h"
#include "sap_moni_ccm.h"

#define ERROR 2 
#define TEMPLATE_SAP_SYSTEMS "sap_systems"

/*=======================================================================
  (C) Copyright SAP AG, 2002

         
 Author  : Dostert/SAP
 Project : Get data from R/3 using XMB
 Using   : RFCSDK 
 ========================================================================*/

void usage(char *progname) {
        #define BL printf(



         BL"Agent\n\n");
         BL"Syntax: %s <System> <RFC-Template>\n\n",  progname     );


         BL"       <RFC-Template> defined in %s\n", AGENT_LOGIN_FILE  );
}



int main(int argc, char **argv) {
	int i,j;

	RFC_HANDLE rfc_handle;
	AlMoniHandle_T *MoniHandle; 
	int   NrOfMoniTempl;
	AlMoniTemplate_T *moni_templ; 

	AlMoniNode_T *nodes;
        unsigned int NrOfNodes;	

	int   highest_alert = 0;
	//char  *bg_color;

	if (argc < 3) {
		usage(argv[0]);
		return ERROR;
	}

	if ( sapmon_init(&MoniHandle, &NrOfMoniTempl) >=  AG_FIRST_ERROR) {
		printf("Could not initialize INI-File\n");
		return ERROR;
	}

	if( sapmon_connect(argv[2], &rfc_handle) >=  AG_FIRST_ERROR) {
		printf("Could not log on\n");
		return ERROR;
	}

	
	for (i = 0; i <  NrOfMoniTempl; i++) {
		if ( strcmp(sapmon_get_template_name(MoniHandle[i]), TEMPLATE_SAP_SYSTEMS) != 0) 
			continue;


		moni_templ = get_template_by_handle(MoniHandle[i]);
		sprintf(moni_templ->Pattern[0], "*\\Availability\\*_%s_*\\", argv[1]);
		moni_templ->NumberOfPatterns = 1;
		
		sapmon_request(&rfc_handle, &(MoniHandle[i]), 1 );
		sapmon_request_tree(MoniHandle[i], &nodes, &NrOfNodes);	
	
		for (j = 0; j < NrOfNodes; j++) {
			if (nodes[j].Actualval > highest_alert)
				highest_alert = nodes[j].Actualval;			
			printf("%s\n", nodes[j].Objectname);
			//printf("%s %s %s %s  %s \n",nodes[j].Mtsysid, nodes[j].Mtmcname, nodes[j].Objectname, nodes[j].Mtnameshrt, nodes[j].currentValue);


		}
			
	}

        //Nothing found
        if (NrOfNodes ==  0) {
 	      highest_alert = 3;
              printf("No information gathered! System up?\n");
        } 
		

	//Log off
	sapmon_disconnect(&rfc_handle);	
	if ( highest_alert < 1 || highest_alert > 3 ) {
                highest_alert = 4;
        }	
	return highest_alert -1;
}
