#include "sap_moni.h"
#include "sap_moni_ccm.h"

#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <string.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 BK printf(   
	 
         BK"Agent\n\n");
         BK"Syntax: %s <System> <RFC-Template>\n\n",  progname     );


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

}

int create_hosts_cfg(FILE *f, AlMoniNode_T node) {
/*
define host{
        host_name bcemain
        alias   bcemain_BCE_26
        address 10.17.72.234
        max_check_attempts 5
        notification_interval 30
        notification_period 24x7
        notification_options d,u,r

}
*/

	char buffer[256];
        char *host;
	struct in_addr addr;


	struct hostent* host_s = NULL;

        strcpy(buffer, node.Objectname);
        host = strtok(buffer, "_");

	if ((host_s = gethostbyname(host)) != NULL) {
		memcpy(&addr,host_s->h_addr, host_s->h_length);
	}
		



	fprintf(f,"\n\ndefine host {");	
	fprintf(f,"\n\thost_name      %s", host);	
	fprintf(f,"\n\talias          %s", node.Objectname);	
	fprintf(f,"\n\taddress        %s", inet_ntoa(addr));	
	fprintf(f,"\n\tmax_check_attempts 5");	
	fprintf(f,"\n\tnotification_interval 30");
	fprintf(f,"\n\tnotification_period 24x7");	
	fprintf(f,"\n\tnotification_options d,u,r");	
	fprintf(f,"\n}");	
	return 0;
}

int init_service(FILE *f) {
#define BL fprintf( f, 

	BL "#Generic service definition template\n");
	BL "define service{\n");
        BL "\tname                            generic-service ; The 'name' of this service template, referenced in other service definitions\n");
        BL "\tactive_checks_enabled           1       ; Active service checks are enabled\n");
        BL "\tpassive_checks_enabled          1       ; Passive service checks are enabled/accepted\n");
        BL "\tparallelize_check               1       ; Active service checks should be parallelized (disabling this can lead to major performance problems)\n");
        BL "\tobsess_over_service             1       ; We should obsess over this service (if necessary)\n");
        BL "\tcheck_freshness                 0       ; Default is to NOT check service 'freshness'\n");
        BL "\tnotifications_enabled           1       ; Service notifications are enabled\n");
        BL "\tevent_handler_enabled           1       ; Service event handler is enabled\n");
        BL "\tflap_detection_enabled          1       ; Flap detection is enabled\n");
        BL "\tprocess_perf_data               1       ; Process performance data\n");
        BL "\tretain_status_information       1       ; Retain status information across program restarts\n");
        BL "\tretain_nonstatus_information    1       ; Retain non-status information across program restarts\n");

        BL "\tregister                        0       ; DONT REGISTER THIS DEFINITION - ITS NOT A REAL SERVICE, JUST A TEMPLATE!\n");
        BL "}\n");

        return 0;
}


int create_services_cfg(FILE *f, AlMoniNode_T node, char  *login_templ) {
/*
define service{
        use                             generic-service         ; Name of service template to use

        host_name                       PWDF0487
        service_description             Standard for App.server
        is_volatile                     0
        check_period                    24x7
        max_check_attempts              3
        normal_check_interval           300
        retry_check_interval            1
        contact_groups                  linux-admins
        notification_interval           120
        notification_period             24x7
        notification_options            w,u,c,r
        check_command                   check_sap_instance!PWDF0487_BCE_26!BCE!
        }
*/
	char buffer[256];
	char *host;

	strcpy(buffer, node.Objectname);
	host = strtok(buffer, "_");

	fprintf(f,"\n\ndefine service{");
	fprintf(f,"\n\tuse                             generic-service");
	fprintf(f,"\n\thost_name                       %s", host );
	fprintf(f,"\n\tservice_description             Standard for App.server");
	fprintf(f,"\n\tis_volatile                     0");
	fprintf(f,"\n\tcheck_period                    24x7");
	fprintf(f,"\n\tmax_check_attempts              3");
	fprintf(f,"\n\tnormal_check_interval           300");
	fprintf(f,"\n\tretry_check_interval            1");
	fprintf(f,"\n\tcontact_groups                  linux-admins");
	fprintf(f,"\n\tnotification_interval           120");
	fprintf(f,"\n\tnotification_period             24x7");
	fprintf(f,"\n\tnotification_options            w,u,c,r");
	fprintf(f,"\n\tcheck_command                   check_sap_instance!%s!%s",  node.Objectname, login_templ);
	fprintf(f,"\n}");
        return 0;
}


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;	

	FILE *f_host,
	     *f_service;	
	
	char fn_s[255];
	char fn_h[255];

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

	sprintf(fn_h, "hosts_%s", argv[1]);
	f_host = fopen(fn_h, "w");

	sprintf(fn_s, "services_%s", argv[1]);
	f_service = fopen(fn_s, "w");
	
	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);	
	

		init_service(f_service);

		for (j = 0; j < NrOfNodes; j++) {
			/* Create hosts.cfg*/
			create_hosts_cfg(f_host, nodes[j]);
			
			create_services_cfg(f_service, nodes[j], argv[2]);


			printf("%s \n", nodes[j].Objectname);


		}
	}

        //Nothing found
        if (NrOfNodes ==  0) {
              printf("No information gathered! System up?\n");
        } 
		
	fclose(f_host);
	fclose(f_service);
	printf("%s %s created\n", fn_s, fn_h);

	//Log off
	sapmon_disconnect(&rfc_handle);	
	
	return SAP_OK;
}
