#!/bin/sh -e

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

# additional options for the commands
ECI_LOAD1_OPTIONS=""
ECI_LOAD2_OPTIONS=""
# how many times should eci-load2 be run if it fails?
SYNC_ATTEMPTS=1
# modem firmware
FIRMWARE_FILE1="/usr/local/lib/eciadsl/firmware00.bin"
FIRMWARE_FILE2="/usr/local/lib/eciadsl/synch01.bin"
# a PPP peer to call
PPPD_PEER=""
# an interface to start with ifup
NET_IF=""

# you can use this file to change the default configuration
[ -f /etc/default/eciadsl ] && . /etc/default/eciadsl

# no user-serviceable parts below this line
##############################################################################
case "$ACTION" in
    add)
    ;;
    *)
	exit 0
    ;;
esac

. /lib/udev/hotplug.functions

if [ ! -e "$FIRMWARE_FILE1" ]; then
  mesg "Cannot find $FIRMWARE_FILE1."
  exit 1
fi

if [ ! -e "$FIRMWARE_FILE2" ]; then
  mesg "Cannot find $FIRMWARE_FILE2."
  exit 1
fi

##############################################################################
STAGE=$1
[ "$IFACE_SYNCH" ] || IFACE_SYNCH=$2
[ "$MODEM_CHIPSET" ] || MODEM_CHIPSET=$3

if [ -z "$PRODUCT" ]; then
  mesg "\$PRODUCT is not defined! This script should be run by hotplug."
  exit 1
fi

PRODUCT=$(echo $PRODUCT | sed -e 's#/# #g')
set $PRODUCT ''
VID=$1
PID=$2
RELEASE=$3

# this implicitly also waits for usbfs to be available and /usr to be mounted
wait_for_file /dev/log

if [ "$STAGE" = "stage1" ]; then
    # stage 1: try to upload the loader firmware
    if ! eciadsl-firmware $ECI_LOAD1_OPTIONS \
		0x$VID 0x$PID 0xFFFF 0xEEEE $FIRMWARE_FILE1; then
	mesg "Cannot initialize the modem."
	exit 1
    fi
    exit 0
elif [ "$STAGE" = "stage2" ]; then
    :
else
    mesg "Usage: $0 stage1"
    mesg "       $0 stage2 MODEM_CHIPSET IFACE_SYNC"
    exit 1
fi

# stage 2: try to upload the real modem firmware
COUNT=1
while [ $COUNT -le "$SYNC_ATTEMPTS" ]; do
    RC=0
    eciadsl-synch $ECI_LOAD2_OPTIONS -alt $IFACE_SYNCH -mc $MODEM_CHIPSET \
	0x$VID 0x$PID $FIRMWARE_FILE2 || RC=$?
    [ $RC -eq 0 ] && break

    sleep 1
    COUNT=$(( $COUNT + 1 ))
done

if [ $RC -ne 0 ]; then
    mesg "Synchronization failed (rc=$RC)"
    exit 1
fi

# configure the network connection
if [ "$PPPD_PEER" ]; then
    sleep 5
    pppd call $PPPD_PEER
fi
if [ "$NET_IF" ]; then
    sleep 5
    ifup $NET_IF
fi

exit 0

