#!/bin/bash

### BEGIN INIT INFO
# Provides:          sc_hardware_cdr
# Required-Start:    $remote_fs $syslog 
# Should-Start:      $remote_fs boot.udev hwscan dbus resmgr sc_hardware_prepare
# Required-Stop:     $null
# Should-Stop:       $null
# Default-Start:     2 3 5
# Default-Stop:
# Description:       configure CD devices
### END INIT INFO

#
# have to run before hal daemon
# so add sc_hardware_cdr
# to Should-Start
#

. /etc/rc.status

# include SmartClient hardware helper functions
test -r /usr/lib/smartclient/sc_hardware.sh && . /usr/lib/smartclient/sc_hardware.sh


statusfile=/var/tmp/cdr_configured

hwinfo=/tmp/hwinfo.cdr

Log_Debug_Target=/var/log/smartclient/sc_hardware_cdr
Log_Level_Syslog=$LOG_NEVER
Log_Level_Console=$LOG_INFO


#
# hotplug is used in SL 9.1, 9.2
# but isn't needed in SL 10.0
#
#CONFIGURE_HOTPLUG="yes"

UDEV_RULE_FILE=/etc/udev/rules.d/55-cdrom.rules


case "$1" in
    start)
        # new logfile timestamp
        log $LOG_DEBUG ""
        log $LOG_DEBUG "`date`: starting"

        log -n $LOG_INFO "SmartClient CD-Drive configuration: "

        # checks for /dev/cdrom
        # because udev deletes /dev/*
        #[ -f $statusfile -a -e /dev/cdrom ] && exit 0

        declare -i RELOAD_MODULE_COUNTER=0
        while [ ! -b "$dev" -a $RELOAD_MODULE_COUNTER -lt 3 ]; do

            let RELOAD_MODULE_COUNTER++

            # this will probe for CD-ROM drives
            # and also loads the required kernel modules
            hwinfo --cdrom >$hwinfo
    
            devices=$(awk '/Device File: \/dev\// { print $3 }' $hwinfo)
    
            if [ -z "$devices" ]; then
                log -n $LOG_INFO "no device found "
                rc_status -s
                rc_exit
            fi
    
            # pick first device
            #   TODO? check also for the rest of the devices?
            set $devices
            dev=$1

            # wait for device to appear
            log -n $LOG_INFO "waiting for $dev "
            declare -i i=0
            while [ ! -b $dev -a $i -lt 10 ]; do
                log -n $LOG_INFO "."
                sleep 1
                let i++
            done

            #
            # workaround:
            # sometimes it is required to reload the kernel module
            # hwinfo will reload it
            #
            if [ ! -b $dev ]; then
                log $LOG_DEBUG "device node $dev did not appear in $RELOAD_MODULE_COUNTER try"
                rmmod sr_mod
            fi

        done

        if [ ! -b $dev ]; then
            log $LOG_DEBUG "device node $dev did not appear. Exiting"
            rc_failed
            rc_status -v
            rc_exit
        fi
        log -n $LOG_DEBUG "detected device node $dev"

        # wait for udev
        sleep 2

        # create hwinfo cache file again.
        # this time more information are included
        # (eg. "Device Files")
        hwinfo --cdrom >$hwinfo

        # read hwinfo again and mark cd-recoder
        dev=$(awk '/Device File: \/dev\// { print $3 }
                /Features:.*CD-R/ { print "cdr" }' $hwinfo)
        # eg:  set /dev/hdc /dev/sr0 cdr /dev/hdd
        set $dev


        # needed to create device mount point
        # (this does not happen automatically on some systems)
        # this should create /dev/sr0 if applicable
        # 20061207: is this REALLY needed?
        #log -n $LOG_INFO " recreate device nodes by udev." 
        #/etc/init.d/boot.udev force-reload > /dev/null

        while [ $# -gt 0 ]; do
            log $LOG_INFO " "
        
            dev=$(basename "$1")
            if [ "$2" = "cdr" ]; then
                # CD-Brenner
                shift
                log -n $LOG_INFO "  configuring CD-recorder on /dev/$dev"
                (cd /dev;ln -sf $dev cdrecorder;chmod go-rw $dev)
                if [ -z "$cdrdev" ]; then
                    cdrdev=$dev
                fi
                HOTPLUG_TEMPL=/usr/share/hotplug/DesktopTemplates/cdwriter.desktop
            else
                # CD-ROM
                log -n $LOG_INFO "  configuring CD-ROM on /dev/$dev"
                (cd /dev;ln -sf $dev cdrom;chmod go-rw $dev)
                if [ -z "$cdromdev" ]; then
                    cdromdev=$dev
                fi
                HOTPLUG_TEMPL=/usr/share/hotplug/DesktopTemplates/cdrom.desktop
                # create directory
                # required by hotplug and also used by udev 
                # to create a link from volume name to this directory
                # Otherwise udev only creates a directory with volume name
                [ -d /media/cdrom ] || mkdir -p /media/cdrom
            fi
        
            # create hotplug config
            if [ "$CONFIGURE_HOTPLUG" = "yes" -a -r "$HOTPLUG_TEMPL" ]; then
                [ -d /media/floppy ] || mkdir -p /media/floppy
                sed -e "s:_DEVICE_:/dev/$dev:" \
                    -e "s:_MOUNTPOINT_:/media/cdrom:" \
                    "$HOTPLUG_TEMPL" \
                    > /var/lib/Desktop/$dev.desktop
            fi
        
            shift
        done

        if [ "$cdromdev" -o "$cdrdev" ]; then
            # wegen SUSE 9.2: Falls /dev/cdrom ein Verzeichnis ist,
            # nach /dev/cd umbenennen
            (cd /dev; [ -d cdrom -a ! -e cd ] && mv cdrom cd)
        fi

        # if only a cd-writer is detected
        # link /dev/cdrom to cd-writer device
        if [ -z "$cdromdev" -a -n "$cdrdev" ]; then
            (cd /dev; ln -sf $cdrdev cdrom;chmod go-rw $dev)
        fi

        # create udev rule (only for the first cdrom device)
        #   \s whitespace
        #   \S non-whitespace
        # use udevinfo (e.g. "udevinfo -q all -p /block/hdc") to verify
        UDEV_ID_PATH=`sed -n 's|\s*Device Files:.*/dev/disk/by-path/\([^\S,]*\).*|\1|p' < $hwinfo | head -n 1`
        log $LOG_DEBUG " (UDEV_ID_PATH: $UDEV_ID_PATH)"

        if [ "$UDEV_ID_PATH" ]; then
            cat > $UDEV_RULE_FILE << EOF
# 
# /media/cdrom links. Generated by sc_hardware_cdr
#
SUBSYSTEM=="block", ENV{ID_PATH}=="$UDEV_ID_PATH", SYSFS{removable}=="1", SYMLINK+="cdrom"
EOF
            #/etc/init.d/boot.udev restart
            /etc/init.d/boot.coldplug restart > /dev/null 2>&1
        fi

        #rm $hwinfo
        echo /dev/$dev >$statusfile
        rc_status -v
        #log $LOG_DEBUG " "
        log $LOG_DEBUG "`date`: finished"
        ;;
    stop)
        ;;
    restart)
        rm -f $statusfile
        $0 start
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
esac
