#!/bin/sh
#
# Tags 
# chkconfig: - 30 70
# description: load and unload AEP1000/AEP2000 coprocessor driver 

PATH=/sbin:/usr/sbin:/bin:/usr/bin

# Source function library
if [ -f /etc/init.d/functions ]; then
  . /etc/init.d/functions
elif [ -f /etc/rc.d/init.d/functions ] ; then
  . /etc/rc.d/init.d/functions
else
  exit 0
fi

module=paep
device=/dev/paep0
daemon=/usr/sbin/aepdaemon
prog=aepdaemon

add() {
        awk '/^[:space:]*\[.*\][:space:]*$/ {section=$0;gsub(/^[\[[:space:]]*/,"",section);gsub(/[\][:space:]]*$/,"",section)} \
            /^default = openssl$/ {if(section=="engine") {print "default = aep";next}} \
            {print $0}' /usr/share/ssl/openssl.cnf > /usr/share/ssl/openssl.cnf.new && \
        cat /usr/share/ssl/openssl.cnf.new > /usr/share/ssl/openssl.cnf && rm /usr/share/ssl/openssl.cnf.new
}

remove() {
    awk '/^[:space:]*\[.*\][:space:]*$/ {section=$0;gsub(/^[\[[:space:]]*/,"",section);gsub(/[\][:space:]]*$/,"",section)} \
        /^default = aep$/ {if(section=="engine") {print "default = openssl";next}} \
        {print $0}' /usr/share/ssl/openssl.cnf > /usr/share/ssl/openssl.cnf.new && \
        cat /usr/share/ssl/openssl.cnf.new > /usr/share/ssl/openssl.cnf && rm /usr/share/ssl/openssl.cnf.new
}

start() {
    action $"Loading $module module" insmod ${module}
    RETVAL=$?

    if [ $RETVAL = 0 ] ; then
        rm -f ${device}
        mknod -m600 ${device} c `grep "paep" /proc/devices | head -1 | awk '{print $1}'` 0
    fi

    if [ -r /etc/aep/aeptarg.bin ] ; then
        /usr/sbin/aepload -device ${device} -reset -image /etc/aep/aeptarg.bin > /dev/null 2>&1 > /dev/null
        RETVAL=$?
    else
        rm ${device}
        RETVAL=1
    fi

    if [ $RETVAL = 0 ] ; then
	    add
            echo -n $"Starting $prog: "
            daemon $daemon
            RETVAL=$?
            echo
    else
        rm ${device}
    fi

    if [ $RETVAL = 0 ] ; then
        touch /var/lock/subsys/aep1000
    else
        remove
    fi
}

stop() {
    remove
    echo -n $"Stopping $prog: "
    killproc $daemon
    echo
    action "Unloading $module module" rmmod ${module}
    RETVAL=$?
    if [ $RETVAL = 0 ] ; then
        rm -f ${device}
    fi
    rm -f /var/lock/subsys/aep1000
}

RETVAL=0
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        start
        ;;
    condrestart)
        if grep -q "paep" /proc/devices ; then
                stop
                start
        fi
        ;;
    *)
        echo usage: `basename $0` '[start|stop|restart|condrestart]'
        RETVAL=1
        ;;
esac

exit $RETVAL