#!/bin/bash

if [ $# -lt 4 ]
then
  exit 8
fi

EPSON_PWD=$1
CURR_IP=$2
NEW_IP=$3
GW_IP=$4


CURR_SUBNET=`expr match "$CURR_IP" '\([0-9]*\.[0-9]*\.[0-9]*\)'`

ifconfig eth0:9 down

if ! ifconfig | grep -q "$CURR_SUBNET"
then

  ALIAS_IP=$CURR_IP
  while [ "$ALIAS_IP" == "$CURR_IP" ]
  do
    LAST_BYTE=$(($RANDOM%255))
    if [ "$LAST_BYTE" == "0" ]
    then 
      LAST_BYTE=$(($LAST_BYTE+1))
    fi
    ALIAS_IP="${CURR_SUBNET}.$LAST_BYTE"
  done
  ifconfig eth0:9 $ALIAS_IP up
fi

rm -f /tmp/curl_enpc
curl -k --connect-timeout 10 --max-time 15 'https://'${CURR_IP}'/tcp_setv4.cgi?W_IP8=1&W_IP1='${NEW_IP}'&W_IP2=255.255.255.0&W_IP3='${GW_IP}'&W_IP10=1&W_IP11=0&%7BRP_IP12E2%7D=Enable&W_PRIP1=1' -o /tmp/curl_enpc -s -I -uepson:${EPSON_PWD}
STATUS=$?
echo "curl exit code: $STATUS"

if [ $STATUS -eq 7 -o $STATUS -eq 28 ] || ! [ -f /tmp/curl_enpc ]
then
  exit 1
fi

if cat /tmp/curl_enpc | grep -q 'HTTP/1.1 401 Unauthorized'
then
  exit 2
fi

if [ $STATUS -eq 0 ]
then
  curl -k --connect-timeout 10 --max-time 15 'https://'${CURR_IP}'/reset.cgi' -s -uepson:${EPSON_PWD}
fi
