#!/bin/bash

# This script initializes the data connection of the modem.
# Error messages are sent to syslog(daemon.err) and stderr.
#
# NOTE: stdin and stdout should be the modem device node,
# as when executed from pppd, so these should be left alone,
# messages should only go to stderr.

# Make sure we have a sane PATH
export PATH=/usr/bin:/bin:/usr/sbin:/sbin

statusfile="/dev/.modem-data/status"
connect_status="/dev/.modem-data/connect-status"
connect_log="/var/log/modem-connect"
chatscript="/etc/chatscripts/modem"

function set_connect_status()
{
    echo "$1" > "$connect_status"
    logger -p daemon.info -t modem-connect -- "connect status = $1"
}

#
# Main
#

if [ "$1" = "-d" ]; then
    if [ -f "$connect_status" ]; then
	if [ "$(< "$connect_status")" == "CONNECTED" ]; then
	    set_connect_status "DISCONNECTED"
	fi
    fi
    exit 0
fi

if [ ! -s "$statusfile" ]; then
    logger -s -p daemon.err -t modem-connect -- "no modem status found"
    exit 1
fi

status="$(< "$statusfile")"
if [ "$status" != "READY" ]; then
    logger -s -p daemon.err -t modem-connect -- "modem not ready (status = '$status')"
    exit 1
fi

# Be sure the terminal settings are sane and CR is not converted to LF
stty sane -icrnl

# All seems OK, proceed with the chat script
set_connect_status "CONNECTING"

date="$(date '+%d-%m-%G %k:%M:%S')"
echo "--- start: $date ---" > "$connect_log"

chat -v -e -f "$chatscript" 2>> "$connect_log"
RET=$?

if [ "$RET" -eq 0 ]; then
    echo "--- end: success ---" >> "$connect_log"
else
    echo "--- end: failure ---" >> "$connect_log"
fi

if [ -d /srv/raperca/log ]; then
    cp -f -- "$connect_log" /srv/raperca/log/modem-connect.log
fi

case "$RET" in
    0)
	set_connect_status "CONNECTED"
	;;
    1|2)
	set_connect_status "IO ERROR"
	;;
    3)
	set_connect_status "TIMEOUT"
	;;
    *)
	set_connect_status "NETWORK ERROR"
	;;
esac

exit $RET
