#!/bin/sh
#
# Connect a serial line for diald.
#
# Copyright (c) 1997, 1998 The Meme Factory, Inc.  http://www.meme.com
#
# This code is distributed under the GNU copyright.
#
# May 18, 1997 Karl O. Pinc Support for multiple chat scripts: use
# suspend and a subshell on chat and filter the messages sent to
# dctrl.

IFACE=$1

# Get configuration parameters
. /etc/sysconfig/dialdcfg
. /etc/sysconfig/network-scripts/dialdcfg-${IFACE}

# Get configuration for the interface.
if [ -f network-functions ] ; then
  # Redhat 5.0 style sourcing.
  CONFIG="ifcfg-$IFACE"
  if [ -n "${CLONE}" ] ; then
    CONFIG="${CONFIG}-${CLONE}"
  fi
  . network-functions
  # Sets PARENTDEVNAME in addition to expected config variables.
  source_config
else
  if [ ! -f /etc/sysconfig/network-scripts/ifcfg-$IFACE ] ; then
    error "/etc/sysconfig/network-scripts/ifcfg-$IFACE does not exist"
  fi
  . /etc/sysconfig/network-scripts/ifcfg-$IFACE
fi

# Make an ignorant, yet sophisticated, stab at sending useful
# messages to dctrl.
# This might be better served with REPORT in the chat script.
# Or maybe we'd like to interperet chat's return status.

terminate_message="Chat script (of pid $$) completed.  Terminating dctrl message relay."
prog_name="$(basename $0)"

function shutdown_relay () {
    echo "$terminate_message" > ${CHAT_FIFO}
}

CHATSCRIPT="/etc/sysconfig/network-scripts/chat-${IFACE}"
[ -f $CHATSCRIPT ] || {
  CHATSCRIPT="/etc/sysconfig/network-scripts/chat-${PARENTDEVNAME}"
}

if [ "$VERBOSE_LOGGING" = "yes" ] ; then
  log_chat_stuff=" -v"
fi

if [ -n "${CHAT_FIFO}" -a -n "${FIFO}" -a "${MON_CONNECT}" = "yes" ] ; then
  send_to_dctrl="yes"
  if [ "$VERBOSE_LOGGING" != "yes" ] ; then
    log_chat_stuff=" -V"
  fi
fi

if [ -n "${send_to_dctrl}" ] ; then
  # Deliver chat's log messages to diald for forwarding to dctrl.
  # sed wont work for this folks, it buffers!
  # (Or dctrl wants the file closed after each line.   Dunno.)
  # (Play x&&y <=> !x||!y games to avoid creating a sub-shell.)
  trap shutdown_relay SIGHUP
  trap shutdown_relay SIGKILL
  while read -r m \
             && echo "$m" | grep -v "$terminate_message" > /dev/null 
     do echo "message $m" > ${FIFO}
  done  < ${CHAT_FIFO} \
  &
  relay_pid="$!"
fi

# Talk to the modem.
if [ -n "${send_to_dctrl}" ] ; then
  /usr/sbin/chat -f "${CHATSCRIPT}" \
                 $log_chat_stuff -s 2> ${CHAT_FIFO}
else
  /usr/sbin/chat -f "${CHATSCRIPT}" \
                 $log_chat_stuff
fi
result=$?

if [ -n "${send_to_dctrl}" ] ; then
  # Can't simply kill the process, it won't have had time to
  # deliver all the messages.
  # Send a message through the logging facility so that it arrives in sequence
  # with the prior messages from chat.
  shutdown_relay

  wait $relay_pid
fi

exit $result
