#!/bin/sh
#
#    Copyright (c) 1996-2001 Brocade Communications Systems, Inc.
#
#    Initialization script to start/stop PCMCIA/CardBus services.
#    Based on rc.pcmcia by David Hinds <dahinds@users.sourceforge.net>.
#

CONFIG=/etc
CHECK=/sbin/chkconfig
INSMOD=/sbin/insmod
RMMOD=/sbin/rmmod
CARDMGR=/sbin/cardmgr
PIDFILE=/var/run/cardmgr.pid

if $CHECK verbose ; then
    ECHO='echo -e'
else
    ECHO=:
fi

cleanup()
{
    while read SN CLASS MOD INST DEV EXTRA ; do
	if [ "$SN" != "Socket" ] ; then
	    /etc/pcmcia/$CLASS stop $DEV 2> /dev/null
	fi
    done
}

# Save option values passed in through the environment
for N in PCMCIA PCIC PCIC_OPTS CORE_OPTS CARDMGR_OPTS SCHEME ; do
    V=`eval echo '$'$N` ; if [ "$V" ] ; then eval ENV_$N=\"$V\" ; fi
done

# Source PCMCIA configuration, if available
if [ -f /etc/pcmcia.conf ] ; then
    . /etc/pcmcia.conf
fi

for N in PCMCIA PCIC PCIC_OPTS CORE_OPTS CARDMGR_OPTS SCHEME ; do
    V=`eval echo '$'ENV_$N` ; if [ "$V" ] ; then eval $N=\"$V\" ; fi
done

if [ "$PCIC" = "" ] ; then
    $ECHO "PCIC module not defined in startup options!"
    exit 1
fi

case "$1" in

'start')
    $ECHO "PCMCIA/CardBus daemons:\c"

	if $CHECK pcmcia; then
	    if [ -d /var/lib/pcmcia ] ; then
		SC=/var/lib/pcmcia/scheme
		RUN=/var/lib/pcmcia
	    else
		SC=/var/run/pcmcia-scheme
		RUN=/var/run
	    fi

	    if [ -h $SC -o ! -O $SC ] ; then rm -f $SC ; fi

	    if [ ! -f $SC ] ; then umask 022 ; touch $SC ; fi

	    if [ "$SCHEME" ] ; then umask 022 ; echo $SCHEME > $SC ; fi

	    /bin/grep -F -q pcmcia /proc/devices

	    if [ $? -ne 0 ] ; then
		if [ -d /lib/modules/default ] ; then
		    PC=/lib/modules/default/pcmcia
		else
		    PC=/lib/modules/`uname -r`/pcmcia
		fi

		if [ -d $PC ] ; then
		    $INSMOD $PC/pcmcia_core.o $CORE_OPTS
		    $INSMOD $PC/$PCIC.o $PCIC_OPTS
		    $INSMOD $PC/ds.o
		else
		    exit 1
		fi
	    fi

	    if [ -s $PIDFILE ] && /bin/kill -0 `cat $PIDFILE` 2>/dev/null; then
		$ECHO " cardmgr\c"
	    else
		if [ -r $RUN/stab ] ; then
		    cat $RUN/stab | cleanup
		fi
		if test -x $CARDMGR; then
		    $CARDMGR `cat $CONFIG/cardmgr.options 2> /dev/null` &
		    $ECHO " cardmgr\c"
		fi
	    fi

	    touch /var/lock/subsys/pcmcia 2>/dev/null
	fi

    $ECHO "."
    ;;

'stop')
    if [ -s $PIDFILE ] ; then
        PID=`cat $PIDFILE`
        /bin/kill $PID
        # Give cardmgr a few seconds to handle the signal
        /bin/kill -0 $PID 2>/dev/null && sleep 2 && \
        /bin/kill -0 $PID 2>/dev/null && sleep 2 && \
        /bin/kill -0 $PID 2>/dev/null && sleep 2 && \
        /bin/kill -0 $PID 2>/dev/null
    fi
    /usr/bin/killall -q "CardBus Watcher"
    if /bin/grep -F -q "ds  " /proc/modules ; then
        $RMMOD ds
        $RMMOD $PCIC
        $RMMOD pcmcia_core
    fi
    rm -f /var/lock/subsys/pcmcia
    ;;

*)
    echo "usage: $0 {start | stop}"
    ;;

esac
