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

#define ERROR 2

/*=======================================================================
  (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 <Template> <RFC-Template>\n\n",  progname     );
                                                                  

	 BL"       <Template> defined in %s    \n", AGENT_INI_FILE  );
	 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;
	
	AlMoniNode_T *nodes;
        unsigned int NrOfNodes;	

	char  templ_name[AL_MONI_MAX_TEMPL_NAME_LENGTH];
	int   highest_alert = 0;
	
        char node_info[255];

        char tid_c[85];

        AlMoniTemplate_T *moni_templ;
        BAPITNDEXT *tTreeNodes;

        BAPITID    tid;
        BAPIPAPROP Properties;

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

	strcpy(templ_name, argv[1]);

	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]), templ_name) != 0)
			continue;

		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;			

			  if (strcmp(nodes[j].Objectname,  nodes[j].Mtnameshrt) != 0) {
                                sprintf(node_info, "%s %s = %s", nodes[j].Objectname, nodes[j].Mtnameshrt, nodes[j].currentValue);
                        } else {
                        	sprintf(node_info, "%s %s = <no value>", nodes[j].Objectname, nodes[j].Mtnameshrt);
			}

                        moni_templ = get_template_by_handle(MoniHandle[i]);
                        tTreeNodes = ItGetLine( moni_templ->TreeNodes,j+1);
                        if( strncmp(tTreeNodes->Mtclass,  MT_CLASS_PERFORMANCE, 3) == 0) {
                                memset(&tid, ' ', sizeof(tid));

                                strncpy(tid.Mtsysid, tTreeNodes->Mtsysid, 8);
                                strncpy(tid.Mtmcname, tTreeNodes->Mtmcname, 40);
                                strncpy(tid.Mtnumrange, tTreeNodes->Mtnumrange, 3);
                                strncpy(tid.Mtuid, tTreeNodes->Mtuid, 10);
                                strncpy(tid.Mtclass, tTreeNodes->Mtclass,3);
                                strncpy(tid.Mtindex, tTreeNodes->Mtindex, 10);
                                strncpy(tid.Extindex, tTreeNodes->Extindex, 10);

                                bapi_system_mte_getperfprop(&rfc_handle, &tid, &Properties);

                                strncpy(tid_c, (char *)&tid,84);
                                tid_c[84] = '\0';

/* Nagios expects this format for performance Data
  rta=2.687ms;3000.000;5000.000;0;
   |    |  |    |         |     | |
   |----|--|----|---------|-----|-|----- * Label 
        |--|----|---------|-----|-|----- * Current Value
           |----|---------|-----|-|----- Unit ( UOM = UNIT of Measurement ) 
                |---------|-----|-|----- Warning Threshold
                          |-----|-|----- Critical Threshold 
                                |-|----- Minimum
                                  |----- Maximum
*/
                                //node_info contains "value unit", we need to separate both according to space
                                //Thresholds obtained by rfc call are multiplied by 100, needs to be divided for further use                    
                                int read_runner = 0;
                                int write_runner = 0;

                                char cleaned_currentValue[AL_MONI_MAX_TEXT_LENGTH];
                                for(;nodes[j].currentValue[read_runner] != '\0';read_runner++){
                                        if(nodes[j].currentValue[read_runner] != ' ')
                                                cleaned_currentValue[write_runner++] = nodes[j].currentValue[read_runner];
                                }
                                cleaned_currentValue[write_runner] = '\0';	


				printf("%s=%s | %s=%s;%f;%f;0;\n",
					nodes[j].Mtnameshrt,
                                        cleaned_currentValue,
					nodes[j].Mtnameshrt,
                                        cleaned_currentValue,
                                        ((float)Properties.Treshy2g+(float)Properties.Treshg2y),
                                        ((float)Properties.Treshy2r+(float)Properties.Treshr2y));

				
                        } else {
                                printf("%s\n", node_info);
                        }


		}

	}

        //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;
}
