/*
 * Temperature monitor
 * Copyright (C) Thomas "ShALLaX" Pedley (gentoox@shallax.com)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

#include <fcntl.h>
#include "i2c-dev.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "xbox.h"

int Xcalibur, bt, ct, btf, ctf, cs;
int fd;
char *fname;
char *devfsname = "/dev/i2c/0";
char *nondevfsname = "/dev/i2c-0";

void checkPIC() {
	if ((fd = open(devfsname, O_RDWR)) < 0) {
		if ((fd=open(nondevfsname,O_RDWR))<0) {
			fprintf(stderr, "Error - failed to open EITHER /dev/i2c/0 or /dev/i2c-0\n    - you must be root and have the correct i2c modules loaded.\n");
			exit(1);
		} else {
			fname = malloc (strlen(nondevfsname));
			strncpy (fname, nondevfsname, strlen(nondevfsname));
		}
	} else {
		fname = malloc (strlen(devfsname));
		strncpy (fname, devfsname, strlen(devfsname));
	}
}

void XcaliburTest() {
	unsigned char byte;
	checkPIC();
	fd = open(fname, O_RDWR);
	if (ioctl(fd,I2C_SLAVE_FORCE,XCALIBUR_ADDRESS) < 0) {
		fprintf(stderr,"Error: Could not set address to %d: %s\n",XCALIBUR_ADDRESS,strerror(errno));
		exit(1);
	}

	byte = i2c_smbus_read_byte_data(fd,0x00);
	if (byte != 255) {
		Xcalibur = 1;
	}
}

int main(int argc, char *argv[]) {
	XcaliburTest();
	if ((fd = open(fname, O_RDWR)) < 0) {
		fprintf(stderr, "Error in open(%s): %s\n", fname, strerror(errno));
		return 1;
	}

	if (ioctl(fd,I2C_SLAVE_FORCE,PIC_ADDRESS) < 0) {
		fprintf(stderr,"Error: Could not set address to %d: %s\n",PIC_ADDRESS,strerror(errno));
		return 2;
	}

	ct = i2c_smbus_read_byte_data(fd,CPU_TEMP);
	bt = i2c_smbus_read_byte_data(fd,BOARD_TEMP);
	ctf = ((9.0 / 5.0) * ct) + 32.0;
	btf = ((9.0 / 5.0) * bt) + 32.0;
	cs = i2c_smbus_read_byte_data(fd,FAN_READBACK);
	cs = cs * 2;
	printf("Xboxtemp by ShALLaX (c)\n\n");
	if (Xcalibur != 1) {
		printf("CPU temperature:     %i °C - ", ct);
		printf("%i °F\n", ctf);
		printf("Board temperature:   %i °C - ", bt);
		printf("%i °F\n", btf);
	} else {
		printf("CPU temperature:     ?? °C - ");
		printf("?? °F\n");
		printf("Board temperature:   ?? °C - ");
		printf("?? °F\n");
	}
	printf("Fan speed:           %i%% ", cs);
	if(cs < 20) {
		printf("[!]");
	}
	printf("\n");
	close(fd);

	return 0;
}
