#!/bin/sh
################################################################
# hloadreader.sh
# Richard Luo
# 2008-07-22
################################################################


################################################################
#### $1: module_file_name
#### $2: device file name
#### $3: kernel module name, as show in /proc/device
################
install_module() {

    if [ ! -f $1 ] ; then
        echo "the file $1 not exist in the current dir, exit"
        exit
    fi

    if [ -e $2 ] ; then
        echo "$2 exist, delete it"
        rm -f $2
    fi

    kmod=$3

    # remove previous installed driver.
    major=$(awk "\$2==\"$kmod\" {print \$1}" /proc/devices)
    if [ $major ] ; then
        rmmod $1 || exit
        echo "rmmod $1 ok!"
    fi

    insmod $1
    major=$(awk "\$2==\"$kmod\" {print \$1}" /proc/devices)
    if [ $major ] ; then
        echo ";-) insmod $1 ok, \$major is $major"
    else
        echo ";-) insmod $1 failed, exit!"
        exit 1
    fi

    mknod $2 c $major 0 || exit

    echo "================================================================"
    echo "****************     Reader Module Install OK   ****************"
    echo "================================================================"
}


################################################################
#### $1: process name
################
kill_process() {
    prog=$1

    pid=`pgrep $prog`

    if [ $pid ] ; then
        echo "$prog exist kill it"
        kill -9 $pid
    fi

}

progrm_file_name=treader
module_file_name=ak4_reader.ko
device_file_name=/dev/reader33
kern_module_name=card_reader

case "$1" in

    start)

        kill_process $progrm_file_name

        if [ ! -f $progrm_file_name ] ; then
            echo "the file $progrm_file_name not exist in the current dir, exit"
            exit
        fi

        install_module  ${module_file_name} ${device_file_name} ${kern_module_name} || exit

        ./${progrm_file_name} ${device_file_name} &

        sleep 1

        pid=`pgrep $progrm_file_name`

        if [ $pid ] ; then
            echo "================================================================"
            echo "****************      $progrm_file_name running OK     ****************"
            echo "================================================================"

        else
            echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
            echo "****************  $progrm_file_name running failed !!! ***********"
            echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
        fi

        ;;


    stop)
        kill_process $progrm_file_name
        ;;

    *)
	    echo "Usage: hw_reader_test {start|stop}"
	    exit 1
	    ;;
esac

exit 0


