
#include <Update.h>
#include "FileLib.h"

//*******************************************************
// perform the actual update from a given stream-
//*******************************************************

void performUpdate(Stream &updateSource, size_t updateSize)
{
  if (Update.begin(updateSize))
  {
    size_t written = Update.writeStream(updateSource); // the update happens here
    if (written == updateSize)
    {
      Serial.println("Written : " + String(written) + " successfully");
    }
    else
    {
      Serial.println("Written only : " + String(written) + "/" + String(updateSize) + ". Retry?");
    }

    if (Update.end())
    {
      displayText("OTA done!");
      if (Update.isFinished())
      {
        Serial.println("Update successfully completed. Rebooting.");
      }
      else
      {
        Serial.println("Update not finished? Something went wrong!");
      }
    }
    else
    {
      Serial.println("Error Occurred. Error #: " + String(Update.getError()));
    }
  }
  else
  {
    Serial.println("Not enough space to begin OTA");
  }
}

//*******************************************************
// check given FS for valid update.bin and perform update if available
//*******************************************************

void updateFromFS(void)
{
  FS fs = SD;
  // kickDog();

  // File updateBin = SD.open("EVO.bin");
  File updateBin = fs.open("/Update.bin");
  if (updateBin)
  {
    if (updateBin.isDirectory())
    {
      Serial.println("Error, Update.bin is not a file");
      updateBin.close();
      return;
    }

    size_t updateSize = updateBin.size();

    if (updateSize > 0)
    {
      Serial.println("Try to start update");
      displayText("Beginning Update");
      performUpdate(updateBin, updateSize);
    }
    else
    {
      Serial.println("Error, file is empty");
    }

    updateBin.close();

    // whe finished remove the binary from sd card to indicate end of the process
    //     fs.remove("/Update.bin");
    rebootEspWithReason("Eureka! Success!!");
  }
  else
  {
    Serial.println("Could not load Update.bin from sd root");
  }
}

//*******************************************************
//
//*******************************************************

void rebootEspWithReason(String reason)
{
  Serial.println(reason);
  // digitalWrite(SWITCH5,LOW);
  delay(1000);
  ESP.restart();
}
