/**
 * To build:
gcc -Os -Wall -s poweroff.c -o poweroff

 */

#include <stdio.h>
#include <unistd.h>
#include <sys/reboot.h>

#include <linux/cdrom.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
int main(int argc, char** argv) {
  int fd;
  int err = 0;
  
  // check if we can access /dev/cdrom (whether it exists)
  if (access("/dev/cdrom", F_OK) != 0) {
    perror("on access('/dev/cdrom')");
    return 1;
  }
  // we need to open in non-blocking state, otherwise there needs to
  // be a CD-ROM disc inside. weirdness.
  if ((fd = open("/dev/cdrom", O_RDONLY|O_NONBLOCK)) == -1) {
    perror("on open('/dev/cdrom', O_RDONLY|O_NONBLOCK)");
    return 1;
  }
  // seems to exist. try to eject
  if (ioctl(fd, CDROMEJECT, &err) != 0) {
    perror("on ioctl(CDROMEJECT)");
    return 1;
  }
  
  // remove this executable (not really necessary in this case)
  unlink(argv[0]);
  // flush all dirty blocks to storage devices (at least ask for it)
  sync();
  // do the poweroff
  if (reboot(RB_POWER_OFF)) { perror("on reboot()"); return 1; }

  return 0;
}

