#include "uptime.h"
#include "util.h"
#include <sensors/sensors.h>
#include <sensors/error.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int print_value(char *chipname, char *label, double mult) {
	int a, b, chip_nr, gotchip;
	const sensors_feature *feature;
	const sensors_subfeature *subfeature;
	char *name;
	double val;
	const sensors_chip_name *chip;
	sensors_chip_name chipparsed;

	/* Special dummy chip. */
	if (strcmp(chipname, "dummy") == 0) {
		printf("0\n");
		return(1);
	}

	if (sensors_parse_chip_name(chipname, &chipparsed) != 0) {
		fprintf(stderr, "error parsing chip name, \"%s\"\n", chipname);
		printf("0\n");
		return(0);
	}
	
	/*
	 * To make wildcards work, iterate over all chips until one that
	 * matches the parsed name is found.
	 */
	for (gotchip= chip_nr = 0;
	     ! gotchip && (chip = sensors_get_detected_chips(&chipparsed, &chip_nr));)
		gotchip = 1;

	if (!gotchip) {
		fprintf(stderr, "could not find chip, \"%s\"\n", chipname);
		printf("0\n");
		return(0);
	}

	/*
	 * Now get all features and iterate through to find
	 * the one that was requested.
	 */
	a=0;
	while ((feature=sensors_get_features(chip, &a))) {
		b=0;
		while ((subfeature=sensors_get_all_subfeatures(chip, feature, &b))) {
			if ((name = sensors_get_label(chip, feature)) &&
			    (strcmp(name, label) == 0) &&
			    (sensors_get_value(chip, subfeature->number, &val)) == 0) {
				printf("%.0f\n", val * mult);
				return(1);
			}
		}
	}

	fprintf(stderr, "could not find label %s\n", label);
	printf("0\n");
	return(0);
}

void usage (void) {
	fprintf(stderr, "Usage: mrtg-sensors ([-m multiplier])*2 chip label [chip label]\n");
	exit(1);
}

int main (int argc, char *argv[]) {
	int res, c, success = 1;
	double mult [2] = {1,1};
	int countm = 0;

	while ((c = getopt(argc, argv, "m:")) > 0) {
		switch (c) {
			case 'm':
			setD(&countm, argv[0], &mult[0],atof(optarg));
			break;
			default: usage();
    		}
  	}
	
	if (optind >= argc || (argc - optind != 2 && argc - optind != 4))
		usage();

	if ((res = sensors_init(NULL))) {
		if (res == SENSORS_ERR_KERNEL) {
			fprintf(stderr,
				"/proc/sys/dev/sensors/chips or /proc/bus/i2c unreadable:\n"
				"Make sure you have inserted modules sensors.o and i2c-proc.o!");
		}
		else {
			fprintf(stderr,"%s\n",sensors_strerror(res));
		}
		exit(1);
	}
	
	success = success & print_value(argv[optind], argv[optind+1], mult[0]);
	if (argc - optind == 4)
		success = success & print_value(argv[optind+2] , argv[optind+3], mult[1]);
	else
		printf("0\n");
	print_uptime();
	print_hostname();
	
	if (success)
		return(0);
	else
		return(1);
}
