/* set volume of the startup chime in the PowerMac nvram. 

   Written by Matteo Frigo <athena@fftw.org>.
   $Id: nvsetvol.c,v 1.1 2003/01/11 11:26:30 athena Exp $

   This program is in the public domain.
*/

/* The volume is stored as a byte at address 8 in the parameter ram. */

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

typedef struct {
     unsigned char sig;
     unsigned char cksum;
     unsigned short len;
     char name[12];
} header;

void die(const char *s)
{
     perror(s);
     exit(1);
}

void seek_pram(int fd, int offset)
{
     if (lseek(fd, offset, SEEK_SET) < 0)
	  die("lseek");
}

int find_pram(int fd, int *size)
{
     header buf;
     int offset = 0;
     while(read(fd, &buf, sizeof(header)) == sizeof(header)) {
	  int sz = buf.len * 16;
	  if (!strncmp(buf.name, "APL,MacOS75", 11)) {
	       *size = sz - sizeof(header);
	       return offset + sizeof(header);
	  }
	  offset += sz;
	  seek_pram(fd, offset);
     }
     die("no PRAM found");
}

#define VOLADDR 8

int main(int argc, char *argv[])
{
     int fd, offset, size;
     char *buf;

     fd = open("/dev/nvram", O_RDWR);
     if (fd < 0) die("can't open /dev/nvram");
     
     offset = find_pram(fd, &size);
     buf = malloc(size);
     if (!buf) die("can't malloc()");

     seek_pram(fd, offset);
     if (read(fd, buf, size) != size)
	  die("error reading /dev/nvram");

     printf("current volume is %d\n", buf[VOLADDR]);
     
     if (argc > 1) {
	  buf[VOLADDR] = atoi(argv[1]);

	  seek_pram(fd, offset);
	  if (write(fd, buf, size) != size)
	       die("error writing /dev/nvram");
	  printf("new volume is %d\n", buf[VOLADDR]);
     }
     close(fd);
}
