/* (C) 1996 under GPL, Hans Lermen <lermen@elserv.ffm.fgan.de>,
 * parts of switch_printk_console() stolen from Kevin Buhr <buhr@stat.wisc.edu>
 */


/* klogconsole -l 1 -r 8 */


#include <stdio.h>
#include <unistd.h>
#include <linux/unistd.h>
#include <linux/termios.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <errno.h>

static _syscall3(int, syslog, int, type, char *, bufp, int, len);

static void console_level(int level)
{
  syslog(8,0,level);
}

static void switch_printk_console(int new_console)
{
  int newvt;
  int vt;

  if ((new_console < 1) || (new_console > 8)) {
    fprintf(stderr,"wrong console number\n");
    exit(1);
  }

  newvt = (new_console << 8) | 11;
  vt = open( "/dev/tty1", O_RDONLY );
  if( vt == -1 ) {
    perror("open(/dev/tty1)");
    exit(1);
  }
  if( ioctl( vt, TIOCLINUX, &newvt ) ) {
    perror("ioctl(TIOCLINUX)");
    exit(1);
  }
  close(vt);
}

void usage(void)
{
  printf(
    "USAGE:\n"
    "  klogconsole [-l console_loglevel ] [ -r console ]\n\n"
    "  console_loglevel  0..7 (kernel may dissallow values <5)\n"
    "  console           1..8 console to which printk() dups messages\n" 
  );
  exit(1);
}


main (int argc, char** argv, char** env)
{
  int op,i;
  extern char *optarg;
  extern int optind, opterr;
  
  if (argc <= 1) usage();
  opterr = 0;
  while ((op = getopt(argc, argv, "l:r:")) != EOF) {
    switch (op) {
      case 'l': {
        i=atoi(optarg);
        console_level(i);
        break;
      }
      case 'r': {
        i=atoi(optarg);
        switch_printk_console(i);
        break;
      }
      default: {
        usage();
        /* doesn't return */
      }
    }
  }
  return 0;
}
