#!/bin/bash

display_usage() {
  echo "This program updates FW of the Gener8 ToF Camera, configures PTP and sets a new IP address"
  echo "This assumes that you place the update tarball (ie. release_v2.00.00.tar.gz is in this directory)"
  echo "To reduce github load, all tarballs are not stored here by default"
  echo "usage" [-p] [-c Current IP Address] [-f Future IP Address] [-v Firmware version]
  echo "-p/--ptp        Congfigure PTP"
  echo "-c/--current    Current IP Address"
  echo "-f/--future     Future IP Address"
  echo "-v/--version    Firmware Version (1.00.03/2.00/2.01/2.03/2.05/2.06/2.07)"
  echo "-h/--help       Display this help message"
  echo "Ex.   ./configure_tof.sh -c 192.168.3.90 2.05 -v 2.07 -p"
  }

#Parse options
POSITIONAL=()
while [[ $# -gt 0 ]]
do
key="$1"

case $key in
    -c|--current)
    CURRENT_IP="$2"
    shift
    shift
    ;;
    -f|--future)
    FUTURE_IP="$2"
    shift
    shift
    ;;
   -v|--version)
    VERSION="$2"
    shift
    shift
    ;;
    -p|--ptp)
    PTP=true
    shift
    ;;
    -h|--help)
    display_usage
    exit
    ;;
    *)
    display_usage
    exit 1
    POSITIONAL+=("$1")
    shift
    ;;
esac
done
set -- "${POSITIONAL[@]}"

if [ -z "$CURRENT_IP" ]; then
  echo "You did not provide the current IP address!"
  display_usage
  exit
elif [ -z "$VERSION" ]; then
  echo "You did not provide the FW version!"
  display_usage
  exit
fi

ssh-keygen -f ~/.ssh/known_hosts -R ${CURRENT_IP}

#Invoke update scripts
if [ $VERSION == "1.00.03" ]; then
  tar -xzf release_v1.00.03.tar.gz
  ./automatic_yeti_bin_upload.py ${CURRENT} release_v1.00.03/
  rm -rf release_v1.00.03/
elif [ $VERSION == "2.00" ] || [ $VERSION == "2.01" ] || [ $VERSION == "2.03" ]; then
  echo "this one"
  ./automatic_yeti_bin_upload_v2.py ${CURRENT_IP} release_v"$VERSION".00.tar.gz/
else
  ./automatic_update_all.py ${CURRENT_IP} release_v"$VERSION".00.tar.gz/
fi


#Wait for up to two minutes for update to complete
echo "Waiting for device to complete update....This could take a couple minutes"
sleep 5
LOOP_COUNT=0
MAX_TRY=60
while [ "$LOOP_COUNT" -lt "$MAX_TRY" ];
do ping -W 2 -c1 $CURRENT_IP > /dev/null && break;
LOOP_COUNT=$(expr $LOOP_COUNT + 1)
done

#Failed to communicate after two minutes
if [ "$LOOP_COUNT" -eq "$MAX_TRY" ]; then
  echo "Device failed to come online in time after update, aborting..."
  exit 1
else 
  echo "Device is online after FW update!"
fi

#We dont need to do anything more so just exit
#if [ -z "$FUTURE_IP" ] && [ -z "$PTP" ]; then

#exit
#fi

#Configure PTP if requested
if [ "$PTP" = true ]; then
  echo "Configuring PTP"
  ./configure_ptp.sh $CURRENT_IP
fi

#Set new IP if requested
if [ -n "$FUTURE_IP" ]; then
  echo "we want to change ip"
  ./set_ip.sh $CURRENT_IP $FUTURE_IP
fi

