/* ulcdrom.c - toggle lock ioctl for cdrom
Copyright (C) 2004 Meethune Bhowmick

http://forums.gentoo.org/viewtopic-p-1190847.html#1190847

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
  USAGE: ulcdrom -[l|u]
*/
#include <fcntl.h>
#include <linux/cdrom.h>
#include <sys/ioctl.h>
#include <strings.h>

/*Change CDROM_DEV to your cdrom device
  it HAS to be a device, NOT a symlink
  to a device */
#define CDROM_DEV "/dev/scd0"

/*Error Strings*/
#define ERROR_DEV "Unable to open cdrom!\n"
#define ERROR_U "Unable to unlock cdrom door\n"
#define ERROR_L "Unable to lock cdrom door\n"
#define SUCCESS_L "Locked cdrom door!\n"
#define SUCCESS_U "Unlocked cdrom door!\n"

void printusage(char *progname)
{

    printf("description: lock/unlock cdrom drive\n");
    printf("usage: %s -[l|u]\n\n", progname);
    printf("-l  lock cdrom drive\n");
    printf("-u  unlock cdrom drive\n");
}

int processparam(int argc, char *argv[])
{
    int lockunlock = 1;
    if (argc != 2)
    {
        printusage(argv[0]);
        return -1;
    }
    if (strcmp(argv[1], "-l") == 0)
        lockunlock = 1;
    else if (strcmp(argv[1], "-u") == 0)
        lockunlock = 0;
    else
    {
        printusage(argv[0]);
        return -1;
    }
    return lockunlock;
}
   
int main(int argc, char *argv[])
{
    int cdrom;
    int lockunlock = processparam(argc,argv);
    if (lockunlock == -1) return 1;
   
    if ((cdrom = open(CDROM_DEV, O_RDONLY | O_NONBLOCK)) == -1)
    {
        printf(ERROR_DEV);
        return 1;
    }
    if (ioctl(cdrom, CDROM_LOCKDOOR, lockunlock) == -1)
    {
        if (lockunlock == 1) printf(ERROR_L); else printf(ERROR_U);
        return 1;
    }
    if (lockunlock == 1) printf(SUCCESS_L); else printf(SUCCESS_U);
    return 0;
}

