#!/bin/sh
#
# rc.pcmcia 1.14 1996/06/26 19:00:34 (David Hinds)
#
# This is designed to work in BSD as well as SysV init setups.  See
# the HOWTO for customization instructions.

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
}

# Source PCMCIA configuration, if available
if [ -f /etc/pcmcia.conf ] ; then
    . /etc/pcmcia.conf
else
    PCMCIA=yes
    # Should be either i82365 or tcic
    PCIC=i82365
    # Put socket driver timing parameters here
    PCIC_OPTS=
    # Put pcmcia_core options here
    CORE_OPTS=
fi

EXITCODE=1
for x in "1" ; do

    # Check that PCMCIA is up
    [ ${PCMCIA} = "no" ] && break

    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')
	if [ -s /var/run/cardmgr.pid ] ; then
	    if kill -0 `cat /var/run/cardmgr.pid` 2>/dev/null ; then
		echo "cardmgr is already running"
		break
	    else
		echo "Cleaning up left-over PCMCIA devices..."
		cat /var/run/stab | cleanup
	    fi
	fi
	echo -n "Starting PCMCIA services:"
	PC=/lib/modules/`uname -r`/pcmcia
	SC=/var/run/pcmcia-scheme
	if [ -L $SC -o ! -O $SC ] ; then rm -f $SC ; fi
	if [ ! -f $SC ] ; then umask 022 ; touch $SC ; fi
	if [ -d $PC ] ; then
	    /sbin/insmod $PC/pcmcia_core.o $CORE_OPTS
	    /sbin/insmod $PC/$PCIC.o $PCIC_OPTS
	    /sbin/insmod $PC/ds.o
	    /sbin/cardmgr
	    echo -n " cardmgr"
	else
	    echo " Module directory $PC not found!"
	    break
	fi
	echo "."
	;;

    'stop')
	echo -n "Shutting down PCMCIA services:"
	if killall cardinfo 2>/dev/null ; then echo -n " cardinfo" ; fi
	PID=`cat /var/run/cardmgr.pid`
	kill $PID
	echo -n " cardmgr"
	while kill -0 $PID 2>/dev/null ; do sleep 2 ; done
	/sbin/rmmod ds
	/sbin/rmmod $PCIC
	/sbin/rmmod pcmcia_core
	echo "."
	EXITCODE=0
	;;

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

    *)
	usage
	;;

    esac

done

# Only exit if we're in our own subshell
if [ "${0##*/}" = "rc.pcmcia" ] ; then
    exit $EXITCODE
fi
