2008-06-12 y0shi autohalt.c

GPL
/*  file autohalt.c

    compile simply with gcc -o autohalt autohalt.c
    
    do NOT run as root!
    my /etc/sudoers line is something like:
    
    hiro    bonsai=NOPASSWD:/sbin/shutdown -h -t2 now
    
    (hiro is my user, bonsai is the box)
    
    tested on thinkpad x30 with linux-2.6.24.3
    
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
  int opt;
  int ac_online;
  float energy_now,energy_full;
  float energy_min=0.05;
  
  FILE *ac;
  FILE *enow;
  FILE *efull;
  
  while ((opt = getopt(argc, argv, "hp:")) != -1) {
    switch (opt) {
    case 'h':
      fprintf(stderr, "Usage: [-p min_percent] [-h] this help\n",argv[1]);
      fprintf(stderr, "with no argument min_percent is set to 5\%\n",argv[1]);
      exit(EXIT_FAILURE);
    case 'p':
      energy_min = atoi(optarg)/100;
      break;
    default/* '?' */
      fprintf(stderr, "Usage: [-p min_percent] [-h] this help\n",argv[1]);
      fprintf(stderr, "with no argument min_percent is set to 5\%\n",argv[1]);
      exit(EXIT_FAILURE);
    }
  }  

  printf("minimal battery energy ist set to %2.0f\%\n",100*energy_min);
  
  while (1) {
    ac = fopen("/sys/class/power_supply/AC/online","r");
    if (ac==NULL) {
      printf("Problem beim Oeffnen des files\n");
      fflush(stdout);
      exit(1);
    }
    fscanf(ac,"%i",&ac_online);
    fclose(ac);
    
    if (ac_online==0) {
      enow = fopen("/sys/class/power_supply/BAT0/energy_now","r");
      if (enow==NULL) {
        printf("Problem beim Oeffnen des files\n");
        fflush(stdout);
        exit(1);
      }
      fscanf(enow,"%f",&energy_now);
      fclose(enow);

      efull = fopen("/sys/class/power_supply/BAT0/energy_full","r");
      if (efull==NULL) {
        printf("Problem beim Oeffnen des files\n");
        fflush(stdout);
        exit(1);
      }
      fscanf(efull,"%f",&energy_full);
      fclose(efull);
      
      if (energy_now/energy_full<energy_min) {
        system("sudo /sbin/shutdown -h -t2 now");
        exit(0);
      }
      else sleep(120);
    }
    else sleep(120);
  }
  
  return 0;
  
}