#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

static void
set_policy (const char *policy)
{
	int i;
	/*DEBUG*/ //printf ("set policy %s\n", policy);
	for (i=0; i <= 3; i++) {
		char buf[256];
		FILE *fp;
		snprintf (buf, sizeof(buf),
			  "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_governor", i);
		fp = fopen (buf, "w");
		if (fp != NULL) {
			fprintf (fp, "%s\n", policy);
			/*DEBUG*///printf ("success (I guess)!\n");
			fclose (fp);
		}
	}
}

static int
read_temp (const char *file)
{
	FILE *fp;
	int tmp;

	fp = fopen (file, "r");
	if (fp == NULL)
		return -1;

	if (fscanf (fp, "%d", &tmp) == 1) {
		/*DEBUG*/ //printf ("readtemp %d!\n", tmp);
		fclose (fp);
		return tmp;
	}

	fclose (fp);
	return -1;
}


int
main(int argc, char *argv[])
{
	int overheating = 0;
	system ("modprobe cpufreq_powersave");
	set_policy ("ondemand");
	while (1) {
		int t1, t2;
		t1 = read_temp ("/sys/devices/platform/coretemp.0/temp1_input");
		t2 = read_temp ("/sys/devices/platform/coretemp.2/temp1_input");

		/* temperatures in thousands of deg */

		if (overheating) {
			if (t1 <= 75000 && t2 <= 75000) {
				set_policy ("ondemand");
				overheating = 0;
			}
		} else {
			if (t1 >= 90000 || t2 >= 90000) {
				set_policy ("powersave");
				overheating = 1;
			}
		}

		sleep (5);
	}

	return 0;
}

