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

int main( int argc, char const *argv[] ) {
	int ret, fd;
	uint8_t region;
	struct dvd_authinfo dvd;

	if( argc < 3 ) {
		fprintf( stderr, "Usage: %s <dvd device> <region>\n", argv[ 0 ]);
		return -1;
	}

	ret = ( uint8_t ) strtol( argv[ 2 ], NULL, 10 );
	if( ret <= 0 || ret > 8 ) {
		fprintf( stderr, "Invalid region.\n" );
		return -1;
	}
	for( region = 0x01; ret > 1; ret-- ) {
		region <<= 1;
	}
	region ^= 0xff;

	fd = open( argv[ 1 ], O_RDONLY );
	if( fd < 0 ) {
		fprintf( stderr, "Failed to open %s\n", argv[ 1 ]);
		return -1;
	}

	memset( &dvd, 0, sizeof( struct dvd_authinfo ));
	dvd.format = DVD_SEND_RPC;
	dvd.region = region;
	ret = ioctl( fd, DVDIOCSENDKEY, &dvd );
	close( fd );
	if( ret < 0 ) {
		fprintf( stderr, "Failed to set region. Try with a disc in the drive.\n" );
		return -1;
	}
	
	return 0;
}
