/*
 * Use clamAV scanner module scanning file
 * */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include "base.h"
#include "factor.h"

extern float clamAV_scanner(const char *, struct FactorSet *);

/*
 * @Function:		clamAV_scanner
 * @Input
 * @Return:
 * */
float clamAV_scanner(const char *scanned_file, struct FactorSet *fs)
{
	float diff_time;
	struct timespec start, stop;
	char buff[100], command[50], result[50];

	clock_gettime(CLOCK_MONOTONIC, &start);
	{
		FILE *fptr;
		int infected = 0;

		sprintf(command, "./clamscan %s", scanned_file);
		if (!(fptr = popen(command, "r"))) {
			system_error();
		}

		while (fgets(buff, 100, fptr) != NULL) {
			if (strstr(buff, "Infected files") != NULL) {
				sscanf(buff, "%*s%*s%d", &infected);
			}
			else if (strstr(buff, "Time") != NULL) {
				sscanf(buff, "%*s%f", &diff_time);
			}
		}
		pclose(fptr);

		if (infected > 0)
			printf("scan result: %d file be infected\n", infected);
		else
			printf("scan result: no infected file\n");

		printf("scanner spend: %f ms\n", diff_time*1000);
	}
	clock_gettime(CLOCK_MONOTONIC, &stop);

	diff_time = calc_diff_time(&start, &stop)/1000; /* us */
	fs->t_comp = diff_time; /* us */

	return diff_time;
}
