#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>


int hist_start=0;
int hist_end=0;

int read_temp()
{
  int fd=-1;
  fd = open("/proc/acpi/thermal_zone/THM0/temperature", O_RDONLY);
  if(fd < 0) {
    perror("open");
    return -2;
  }

  char buffer[512];
  int rv=0;
  rv=read(fd, buffer, 512);
  if(rv<0) {
    perror("read");
    return -3;
  }

  int end=0;
  while(buffer[end] != 'C') {
    end++;
  }

  int start=end-2;
  while(buffer[start] != ' ') {
    start--;
  }
  start++;
  buffer[end-1] = '\0';

  int temperature = atoi(buffer+start);
  close(fd);

  return temperature;
}

int write_fan_level(int lvl)
{
  int fd = -1;
  fd = open("/proc/acpi/ibm/fan", O_RDWR);
  if(fd<0) {
    perror("open");
    return -1;
  }
  char cmd[128];
  *cmd='\0';
  
  sprintf(cmd, "level %d", lvl);
  int rv=write(fd, cmd, strlen(cmd));
  if(rv<0) {
    perror("write fan level");
    return -2;
  }

  close(fd);
}

int enable_watchdog()
{
  int fd = -1;
  fd = open("/proc/acpi/ibm/fan", O_RDWR);
  if(fd<0) {
    perror("open");
    return -1;
  }
  char *cmd = "watchdog 10";
  
  int rv=write(fd, cmd, strlen(cmd));
  
  if(rv<0) {
    perror("enable watchdog");
    return -2;
  }

  close(fd);
}

void run_control_loop()
{
  int cur_temp=0;
  int last_temp=0;
  int lvl=0;
  
  while(1) {
    int rising=0,
        falling=0;
    cur_temp = read_temp();

    if(cur_temp > last_temp)  rising = 1;
    else if(cur_temp < last_temp) falling = 1;
    
    if(rising && cur_temp > 55) {
      if(lvl<7) lvl++;
    } else if(falling && cur_temp < 46) {
      if(lvl>0) lvl--;
    }
    last_temp = cur_temp;
    write_fan_level(lvl);
    usleep(1000*1000*2);
  }
}


int main(int argc, char* argv [])
{
  int opt=-1;
  enable_watchdog();
  while((opt = getopt(argc, argv, "w:rcd")) != -1)
  {
    switch(opt)
    {
      case 'd':
        daemon(0,0);
        break;
      case 'w':
        write_fan_level(atoi(optarg));
        break;
      case 'r':
        printf("Temperature is: (%d C)\n", read_temp());
        break;
      case 'c':
        run_control_loop();
        break;
    }
  }

  return 0;
}
