#!/usr/bin/sh

SPOOL=/var/spool/hylafax

DEVICE="$1"

case "$DEVICE" in
    tty*)
        SYSLOG=local6.info
        FAXGETTY=/usr/sbin/faxgetty
        ;;
    boston*)
        SYSLOG=local5.info
        FAXGETTY=/usr/sbin/btgetty
        PID_WAIT_FILE=/var/run/btcalld.pid
        PID_WAIT_PRG=btcalld
        ;;
    sip*)
        SYSLOG=local4.info
        FAXGETTY=/usr/sbin/ifaxgetty
        PID_WAIT_FILE=/var/run/ifaxcalld.pid
        PID_WAIT_PRG=ifaxcalld
        ;;
    *)
        echo "Bad device: $DEVICE" >&2
        exit -1;
esac

if [ -f /etc/hylafax/wrapper.sh ]
then
    . /etc/hylafax/wrapper.sh
fi

cd $SPOOL
# Make sure device status file has the right user rights or *getty
# won't be able to update them if we create them with root as owner.
touch status/$DEVICE
chown uucp. status/$DEVICE

while [ -f HALT ]
do
        MSG=$(cat HALT)
        echo "HALT: $MSG" > status/$DEVICE
        sleep 10
done


if [ -f .restart ]
then
        logger -p $SYSLOG -t getty-wrapper "Restarting..."
        echo "Restarting..." > status/$DEVICE

        while [ -f .restart ]
        do
                sleep 1
        done
fi

if [ -n "$PID_WAIT_FILE" ]
then
    echo -n "Checking for $PID_WAIT_FILE pid" 1>&2
    WAITED=no
    while [ ! -f $PID_WAIT_FILE ]
    do
        if [ $WAITED = no ];
        then
                logger -p $SYSLOG -t getty-wrapper "Waiting for $PID_WAIT_FILE"
                echo "Waiting for $PID_WAIT_PRG" > status/$DEVICE
        fi
        echo -n "."
        sleep 1
        WAITED=yes;
    done

    if [ $WAITED = yes ];
    then
        sleep 10;
    fi
    p=`grep '^[1-9][0-9]*$' $PID_WAIT_FILE`

    echo " $p"

    f=$(readlink /proc/$p/exe)
    kill -0 $p >/dev/null 2>&1

    if [ $? = 0 ] && [ $(basename $f) == "$PID_WAIT_PRG" ]
    then
        echo "PID $p running as $f"
        sleep 3;
    else
        echo "No process running"
        exit
    fi
fi

exec $FAXGETTY "$DEVICE"
