#!/bin/sh

# As far as I could test, if the CD-ROM is unregistered, subsequent
# registrations will only cause kernel OOPS. So don't do it more than
# once (we test /proc/ide/ide[0-1] to know).

# Set a secure path
PATH=/sbin:/usr/sbin:/bin:/usr/bin

# The IDE channel which has the CD-ROM
IDE_NR=1

# The settings for the ide channels (first ioport, second ioport and IRQ,
# separated by spaces).
IDE0_PARAMS="0x1f0 0x3f6 14"
IDE1_PARAMS="0x170 0x376 15"

# This is a dummy ide device that is always connected. Just a way to get
# to the IDE driver. This device is not modifyied.
IDE0_USE_DEV=/dev/hdc
IDE1_USE_DEV=/dev/hda

# Evaluate the parameters based on the IDE CD channel
eval "IDE_PARAMS=\"\$IDE${IDE_NR}_PARAMS\""
eval "IDE_USE_DEV=\$IDE${IDE_NR}_USE_DEV"

register () {
	if [ -d /proc/ide/ide${IDE_NR} ]; then
		echo "The device is already registered or not fully"
		echo "unregistered. Registering again will cause many"
		echo "problems (currently registration/unregistration"
		echo "can be done only once)."
		exit 1
	fi
	hdparm -R $IDE_PARAMS $IDE_USE_DEV
}

unregister () {
	if ! modprobe -r -q ide-cd ; then
		echo "CD-ROM modules are being used. Cannot unload."
		echo "Disc still mounted? Playing an Audio-CD?"
		exit 1
	fi
	hdparm -U $IDE_NR $IDE_USE_DEV
}

case "$1" in
  on)
	register
	;;
  off)
	unregister
	;;
  rescan)
	register
	unregister
	;;
  *)
	echo "Usage: $0 {on|off|rescan}"
	echo "Registers the removable CD-ROM with the system."
	exit 1
esac

exit $?
