#!/bin/sh

# with small changes for muLinux
# by M. Andreoli

#set -x


usage()
{
    echo "Usage: $0 {start|stop|restart}"
}
cleanup()
{
    while read SN CLASS MOD INST DEV EXTRA ; do
	if [ "$SN" != "Socket" ] ; then
	    /etc/pcmcia/$CLASS stop $DEV 2> /dev/null
	fi
    done
}
if [ -f /etc/pcmcia.conf ] ; then
    . /etc/pcmcia.conf
else
    PCIC=i82365
    PCIC_OPTS=
    CORE_OPTS=
    CARDMGR_OPTS=
    SCHEME=
fi
if [ "$PCMCIA" -a "$PCMCIA" != "yes" ] ; then exit 0 ; fi
EXITCODE=1
for x in "1" ; do

    if [ "$PCIC" = "" ] ; then
	echo "PCIC not defined in rc.pcmcia!"
	break
    fi

    if [ $# -lt 1 ] ; then usage ; break ; fi
    action=$1

    case "$action" in

    'start')
	echo -n "Starting PCMCIA services:"
	SC=/var/run/pcmcia-scheme
	if [ -L $SC ] ; then rm -f $SC ; fi
	if [ ! -f $SC ] ; then umask 022 ; echo > $SC ; fi
	if [ "$SCHEME" ] ; then umask 022 ; echo $SCHEME > $SC ; fi
	grep pcmcia  /proc/devices 2>/dev/null
	if [ $? -ne 0 ] ; then
	    PC=/lib/modules/2.0.36/pcmcia
	    if [ -d $PC ] ; then
		echo -n " modules"
		/usr/bin/insmod $PC/pcmcia_core.o $CORE_OPTS
		/usr/bin/insmod $PC/$PCIC.o $PCIC_OPTS
		/usr/bin/insmod $PC/ds.o
	    else
		echo " module directory $PC not found."
		break
	    fi
	fi
	if [ -s /var/run/cardmgr.pid ] && \
	   kill -9 `cat /var/run/cardmgr.pid` 2>/dev/null ; then
	    echo " cardmgr is already running."
	else
	    if [ -r /var/run/stab ] ; then
		cat /var/run/stab | cleanup
	    fi
	    echo " cardmgr."
	    /usr/bin/cardmgr $CARDMGR_OPTS
	fi
	;;

    'stop')
	echo -n "Shutting down PCMCIA services:"
	PID=`cat /var/run/cardmgr.pid 2>/dev/null`
	kill -9 $PID 2>/dev/null
	sleep 1 ; kill -9 `pidof cardmgr` 2>/dev/null
	echo -n " cardmgr"

	if grep "ds" /proc/modules >/dev/null ; then
	    echo  " modules."
	    /usr/bin/rmmod ds
	    /usr/bin/rmmod $PCIC
	    /usr/bin/rmmod pcmcia_core
	else
	    echo  "."
	fi
	rm -f /var/lock/subsys/pcmcia
	EXITCODE=0
	;;

    'restart')
	$0 stop
	$0 start
	EXITCODE=0
	;;

    *)
	usage
	;;

    esac

done
exit $EXITCODE
