#! /bin/sh
# /etc/r2d2/devices/serial_if - initialize the serial ports
#
# Copyright Winfried Tr\374mper <winni@xpilot.org> 1996,1997. All rights reserved.
# This file is part of the r2d2 init-concept.
#


SERIAL_CFG="/etc/hardware/serial_if.conf"
#SERIAL_CFG="./serial_if.conf"    #DEBUG (FOR TESTING ONLY)


    # oct_perm() computes the ocatal value of a simple symbolic file permission
function oct_perm () {
    local permissions n m pre post patt oct_val
    permissions="$1"

      # in case somebody used cut&paste (argh!)
    permissions=${permissions#c}
    permissions=${permissions#b}

      # theory of operation: we shift the dash in -???????? from left to right
      # and match against the symbloc permissions. If - doesn't match we assume
      # r, w or x respectivly. Of course this is all too easy.
    pre=""
    post="????????"
    oct_val="777"
    for m in 100 10 1
    do
        for n in 4 2 1
        do
            patt="$pre-$post"
            case "$permissions" in
                $patt)
                    oct_val=$[ $oct_val-$n*$m ]
                    ;;
            esac
            pre="?$pre"
            post=${post#?*}
        done
    done
    echo $oct_val
}


echo "$0: configuring serial interfaces through $SERIAL_CFG ..."

# Do wild interrupt detection?
# [This is a ugly hack to guarantee backwards compatibility. If you use r2d2
#  in combination with SysV init, move the command into runlevel.conf at no. 10]
#
#setserial -W /dev/ttyS0


while read DEVICE OWNER GROUP PERMISSIONS PARAMETERS
do
      # ignore comments and blank lines
    case "$DEVICE" in
        \#* | "")
	    continue
	    ;;
	default*|DEFAULT*)
	    DFLT_OWNER="$OWNER"
	    DFLT_GROUP="$GROUP"
	    DFLT_PERM="$PERMISSIONS"
	    DFLT_PARAM="$PARAMETERS"
	    continue
	    ;;
    esac

    echo -ne "$PERMISSIONS $OWNER\011$GROUP   "


      # "*" stands for "any permissions" (leave everything as it is)
    
    if [ "$OWNER" != "*" ]
    then
	chown  $OWNER  $DEVICE

    elif [ "$DFLT_OWNER" != "-" ]
    then
	chown  $DFLT_OWNER  $DEVICE
    fi


    if [ "$GROUP" != "*" ]
    then
	chgrp  $GROUP  $DEVICE

    elif [ "$DFLT_GROUP" != "-" ]
    then
	chgrp  $DFLT_GROUP  $DEVICE
    fi


    if [ "$PERMISSIONS" != "*" ]
    then
	permissions=`oct_perm "$PERMISSIONS"`
	chmod $permissions $DEVICE

    elif [ "$DFLT_PERM" != "-" ]
    then
	permissions=`oct_perm "$DFLT_PERM"`
	chmod $permissions $DEVICE
    fi


    setserial -v  $DEVICE  $DFLT_PARAM  $PARAMETERS

done < $SERIAL_CFG


echo "$0: configuring serial devices done."
exit 0

# If the setserial above locks something up, we may not have _any_ 
# debug information. So we use '-v' above already.
#setserial -bg /dev/ttyS*
