#!/bin/sh -e

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

# You must copy the correct values from /usr/share/doc/eciadsl/modems.db.
# Do not forget the leading "0x"!
# If they are all 0, then the values passed by the kernel are used.
# This is recommended.
VID1=0
PID1=0
VID2=0
PID2=0
# 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

PROGNAME=$0

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

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

if [ ! -f /proc/bus/usb/devices ]; then
  if ! mount -t usbdevfs none /proc/bus/usb 2> /dev/null; then
    echo "Cannot mount the USB device filesystem."
    exit 1
  fi
fi

##############################################################################
if [ -z "$PRODUCT" ]; then
  echo "\$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

case "$PROGNAME" in
    *eciadsl1)
	STAGE=1
	if [ "$VID1" -eq 0 -a "$VID2" -eq 0 ]; then
	    VID1=0x$VID
	    PID1=0x$PID
	    VID2=0xFFFF
	    PID2=0xEEEE
	fi
    ;;
    *eciadsl2)
	STAGE=2
	if [ "$VID1" -eq 0 -a "$VID2" -eq 0 ]; then
	    VID2=0x$VID
	    PID2=0x$PID
	fi
    ;;
    *)
	echo "Program called with the wrong name."
	exit 1
    ;;
esac

# try to upload the loader firmware
if [ "$STAGE" -eq 1 ]; then
    if eciadsl-firmware $ECI_LOAD1_OPTIONS \
		$VID1 $PID1 $VID2 $PID2 $FIRMWARE_FILE1; then
	exit 0
    else
	echo "Cannot initialize the modem."
	exit 1
    fi
fi

# try to upload the real modem firmware
COUNT=1
RET=1
while [ $COUNT -le "$SYNC_ATTEMPTS" -a $RET -ne 0 ]; do
    eciadsl-synch $ECI_LOAD2_OPTIONS $VID2 $PID2 $FIRMWARE_FILE2
    RET=$?
    [ $RET -eq 0 ] && break

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

if [ $RET -ne 0 ]; then
    echo "Synchronization failed (rc=$RET)"
    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

