#!/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).

# UPDATE: this appears to be the case on the HP Omnibook 4150 but not on the
# Dell Inspiron 8500 laptop.

# WARNING: Doing this can be dangerous. See the hdparm man page.

# !!!!!!!!!!!!!!!!!!!! YOU HAVE BEEN WARNED !!!!!!!!!!!!!!!!!!!!!!!!!

# 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
	# If using ide-scsi be sure to unload CD related modules
	# so that they pick up SCSI emulation when loading again
	if LC_ALL=C grep -q "ide-scsi" /proc/cmdline ; then
		modprobe -r ide-scsi > /dev/null 2>&1
		modprobe -r ide-cd > /dev/null 2>&1
	fi
	hdparm -R $IDE_PARAMS $IDE_USE_DEV
	# If using ide-scsi attempt to get it
	if LC_ALL=C grep -q "ide-scsi" /proc/cmdline ; then
        	modprobe ide-scsi >/dev/null 2>&1
	fi
	# update fstab and device links
	updfstab
}

unregister () {
	if ! modprobe -r -q ide-scsi ; then
		echo "SCSI emulation of CD-ROM still being used. Cannot unload."
		echo "Disc still mounted? Playing an Audio-CD?"
		exit 1
	fi
	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
	# update fstab and device links
	updfstab
}

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 $?
