/*
 * Copyright (c) 2004 MiracleNet Group
 *  Chatchawan Wongsiriprasert (cws@miraclenet.co.th).
 *   2004/12/03 
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *
 *  This product includes software developed by Miraclenet Group 
 *    (www.miraclenet.co.th) Thailand and its contributors.
 * 
 * 4. Neither the name of the company nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <fcntl.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/consio.h>

main(int argc,char* argv[])
{
  int f,n,i,uid;
  char buf[100];
  struct stat sb;

  if ( argc < 2 )
  {
	fprintf(stderr,"usage %s : number\n",argv[0]);
	return 1;
  }
  n = atoi(argv[1]);
  if ( n < 1 || n > 16 )
  {
	fprintf(stderr,"console number %d out of range\n",n);
	return 1;
  }

  //caller must own one vt screen.
  uid = getuid();
  for(i = 0;i <= 16; ++i)
  {
	  snprintf(buf,sizeof(buf),"/dev/ttyv%x",i);
	  if ( stat(buf,&sb) != 0 ) continue;

	  if ( uid == sb.st_uid ) break;
  }

  if ( i == 16 )
  {
	  fprintf(stderr,"no virtual console owned by the user\n");
	  return 2;
  }
	  
  f=open("/dev/console",O_RDWR);
  if ( f < 0 ) 
  {
	perror("Can not open console");
	return 1;
  }

  if (ioctl(f, VT_ACTIVATE, (caddr_t) (long) n) == -1)
                perror("ioctl(VT_ACTIVATE)");
  close(f);

  return 0;
}

