#!/bin/bash
# -*- Mode: shell-script -*-
# Copyright (C) 2003 by MandrakeSoft, Chmouel Boudjnah <chmouel@mandrakesoft.com>
# Redistribution of this file is permitted under the terms of the GNU
# Public License (GPL)
#
# suspend: 40
# resume: 15
#

. /etc/sysconfig/suspend

ARG=$1

if [[ $RESTART_PCMCIA != "yes" ]];then
    exit;
fi

if [[ -x /sbin/pccardctl && -d /sys/class/pcmcia_socket ]]; then
    USE_SYSFS=yes
    CARDCTL=/sbin/pccardctl
else
    USE_SYSFS=
    CARDCTL=/sbin/cardctl
fi

function suspend {
    if [[ $PCMCIA_BIOS_BUG == "yes" ]];then
	$CARDCTL eject
	wait_for_cards_removal
    else
	$CARDCTL suspend
    fi
}

function wait_for_cards_removal {
    if [[ $PCMCIA_WAIT == "yes" ]];then
	if [[ -z "$USE_SYSFS" ]]; then
	    stabs=
	    for s in /var/run/stab /var/lib/pcmcia/stab; do
		[ -f $s ] && stabs="$stabs $s"
	    done
	    if [ -z $stabs ]; then
		logger "No pcmcia stab file, not waiting for PCMCIA device removal"
		return;
	    fi
	    while grep '^Socket' $stabs 2>/dev/null | grep -qv 'empty$'; do
		logger "Waiting for pcmcia-device to be removed..."
		sleep $PCMCIA_TIMEOUT
	    done
	else
	    test_cards_present () {
		local c

		for c in /sys/class/pcmcia_socket/*/card_type; do
		    cat $c > /dev/null 2>&1 && return 0
		done

		return 1
	    }

	    while test_cards_present; do
		logger "Waiting for pcmcia-device to be removed..."
		sleep $PCMCIA_TIMEOUT
	    done
        fi
    fi
}

function resume {
    if [ $PCMCIA_BIOS_BUG == "yes" ]; then
	$CARDCTL insert
    else
	$CARDCTL resume
    fi
}

case $ARG in
    suspend)
	suspend
	;;
    resume)
	resume
	;;
esac
