/* ibook-led
 * Nico Schottelius (nico-linux@schottelius.org)
 * 2005-02-18
 * v0.3
 * control the frond led of an ibook (powerbook?) via userspace
 */

/* open() */
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

/* write */
#include <unistd.h>

/* Linux */
#define ADB_DEVICE "/dev/adb"

static inline void error()
{
   write(2,"ibook-led <0,1,2> <delay>\n",27);
   write(2,"   0: switch led off\n",22);
   write(2,"   1: switch led on\n",21);
   write(2,"   2: switch led on for <delay> useconds\n",42);
   
   exit(1);
}

int main(int argc, char **argv)
{
   int fd = 0;
   char adb_on[5], adb_off[5];

   /* on: 4, 0xee, 4, 0, 1 */
   adb_on[0] = 0x06;
   adb_on[1] = 0xee;
   adb_on[2] = 0x04;
   adb_on[3] = 0x00;
   adb_on[4] = 0x01;

   /* off: 4, 0xee, 4, 0, 0 */
   adb_off[0] = 0x06;
   adb_off[1] = 0xee;
   adb_off[2] = 0x04;
   adb_off[3] = 0x00;
   adb_off[4] = 0x00;

   if(argc < 2) error();
//   if(argc < 2 || argc > 3) error();

   /* open /dev/adb */
   if((fd = open(ADB_DEVICE,O_RDWR)) == -1) return 1;

   switch(atoi(argv[1])) {
      case 0: 
         /* write off */
         if(!write(fd,adb_off,5)) return 2;
         break;

      case 1: 
         /* write on */
         if(!write(fd,adb_on,5)) return 3;
         break;

      case 2: 
         /* check delay */
         if(argc!=3) error();

         /* write on */
         if(!write(fd,adb_on,5)) return 4;

         /* sleep */
         //usleep(1000000);
         usleep(atoi(argv[2]));
   
         /* write off */
         if(!write(fd,adb_off,5)) return 5;

         break;

      /* some kind of fun, should have a signal handler to switch off*/
      case 3: 
         while(1) {
            /* write on */
            if(!write(fd,adb_on,5)) return 6;
            usleep(100000);
            if(!write(fd,adb_off,5)) return 7;
            usleep(100000);
         }
      
      default:
         error();
         break;
   }
 
   return close(fd);
}
