// GxEPD2_WiFi_CertStore_Loader : Display Library example for SPI e-paper panels from Dalian Good Display and boards from Waveshare.
// Requires HW SPI and Adafruit_GFX. Caution: the e-paper panels require 3.3V supply AND data lines!
//
// Display Library based on Demo Example from Good Display: https://www.good-display.com/companyfile/32/
//
// Author: Jean-Marc Zingg
//
// Version: see library.properties
//
// Library: https://github.com/ZinggJM/GxEPD2

// Supporting Arduino Forum Topics (closed, read only):
// Good Display ePaper for Arduino: https://forum.arduino.cc/t/good-display-epaper-for-arduino/419657
// Waveshare e-paper displays with SPI: https://forum.arduino.cc/t/waveshare-e-paper-displays-with-spi/467865
//
// Add new topics in https://forum.arduino.cc/c/using-arduino/displays/23 for new questions and issues
//
// This example is used to download the https certificate archive to LittleFS for ESP8266 WiFiClientSecure cert store
//
// See also https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266WiFi/examples/BearSSL_CertStore
//
// If you need an updated certs.ar, take a look at subdirectory update_certs
// update_certs needs an openssl commandline tool. I downloaded it from https://kb.firedaemon.com/support/solutions/articles/4000121705
//
// NOTE: this utility example is only useful for ESP8266

#if defined(ESP32)
#include "SPIFFS.h"
// set formatOnFail = true for initial format of ESP32 SPIFFS (e.g. if error occured)
const bool formatOnFail = false;
#endif

#include <FS.h>

#if defined (ESP8266)
#include <LittleFS.h>
#include <ESP8266WiFi.h>
#endif

#include <WiFiClient.h>
#include <WiFiClientSecure.h>

const char* ssid     = "........";
const char* password = "........";
const int httpPort  = 80;
const int httpsPort = 443;

const char github_io_pem [] PROGMEM = R"CERT(
-----BEGIN CERTIFICATE-----
MIIEyDCCA7CgAwIBAgIQDPW9BitWAvR6uFAsI8zwZjANBgkqhkiG9w0BAQsFADBh
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBH
MjAeFw0yMTAzMzAwMDAwMDBaFw0zMTA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AECAzANBgkqhkiG
9w0BAQsFAAOCAQEAkPFwyyiXaZd8dP3A+iZ7U6utzWX9upwGnIrXWkOH7U1MVl+t
wcW1BSAuWdH/SvWgKtiwla3JLko716f2b4gp/DA/JIS7w7d7kwcsr4drdjPtAFVS
slme5LnQ89/nD/7d+MS5EHKBCQRfz5eeLjJ1js+aWNJXMX43AYGyZm0pGrFmCW3R
bpD0ufovARTFXFZkAdl9h6g4U5+LXUZtXMYnhIHUfoyMo5tS58aI7Dd8KvvwVVo4
chDYABPPTHPbqjc1qCmBaZx2vN4Ye5DUys/vZwP9BFohFrH/6j/f3IL16/RZkiMN
JCqVJUzKoZHm1Lesh3Sz8W2jmdv51b2EQJ8HmA==
-----END CERTIFICATE-----
)CERT";

const char* host_rawcontent  = "raw.githubusercontent.com";
const char* path_certstore_raw   = "/ZinggJM/GxEPD2/master/examples/GxEPD2_WiFi_CertStore_Loader/";
const char* fp_github_io     = "97:D8:C5:70:0F:12:24:6C:88:BC:FA:06:7E:8C:A7:4D:A8:62:67:28"; // SHA-1 as of 12.04.2024

void setup()
{
  Serial.begin(115200);
  Serial.println();
  Serial.println("GxEPD2_WiFi_CertStore_Loader");

#ifdef RE_INIT_NEEDED
  WiFi.persistent(true);
  WiFi.mode(WIFI_STA); // switch off AP
  WiFi.setAutoConnect(true);
  WiFi.setAutoReconnect(true);
  WiFi.disconnect();
#endif

  if (!WiFi.getAutoConnect() || ( WiFi.getMode() != WIFI_STA) || ((WiFi.SSID() != ssid) && String(ssid) != "........"))
  {
    Serial.println();
    Serial.print("WiFi.getAutoConnect()=");
    Serial.println(WiFi.getAutoConnect());
    Serial.print("WiFi.SSID()=");
    Serial.println(WiFi.SSID());
    WiFi.mode(WIFI_STA); // switch off AP
    Serial.print("Connecting to ");
    Serial.println(ssid);
    WiFi.begin(ssid, password);
  }
  int ConnectTimeout = 30; // 15 seconds
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
    Serial.print(WiFi.status());
    if (--ConnectTimeout <= 0)
    {
      Serial.println();
      Serial.println("WiFi connect timeout");
      return;
    }
  }
  Serial.println();
  Serial.println("WiFi connected");

  // Print the IP address
  Serial.println(WiFi.localIP());

  setClock();

#if defined (ESP8266)
  LittleFS.begin();
  Serial.println("LittleFS started");
  //LittleFS.remove("certs_list.txt"); // was used for test
  LittleFS.remove("certs.ar");
  LittleFS.remove("certs.idx");
#elif defined (ESP32)
  SPIFFS.begin();
  Serial.println("SPIFFS started");
  //SPIFFS.remove("certs_list.txt"); // was used for test
  SPIFFS.remove("certs.ar");
  SPIFFS.remove("certs.idx");
#endif
  listFiles();
  //downloadFile_HTTPS(host_rawcontent, path_certstore_raw, "certs_list.txt", "certs_list.txt"); // was used for test
  downloadFile_HTTPS(host_rawcontent, path_certstore_raw, "certs.ar", "certs.ar");
  listFiles();
}

void loop()
{
}

void downloadFile_HTTPS(const char* host, const char* path, const char* filename, const char* target)
{
  // Use WiFiClientSecure class to create TLS connection
#if defined (ESP8266)
  BearSSL::WiFiClientSecure client;
//  BearSSL::X509List cert(cert_DigiCert_TLS_RSA_SHA256_2020_CA1);
//  BearSSL::X509List cert_pem_first(github_io_chain_pem_first);
//  BearSSL::X509List cert_pem_second(github_io_chain_pem_second);
//  BearSSL::X509List cert_pem_third(github_io_chain_pem_third);
  BearSSL::X509List cert_pem(github_io_pem);
#else
  WiFiClientSecure client;
#endif
  Serial.println(); Serial.print("downloading file \""); Serial.print(filename);  Serial.println("\"");
  Serial.print("connecting to "); Serial.println(host);
#if defined (ESP8266)
  //client.setInsecure(); // fallback, currently still works with BearSSL
  //client.setFingerprint(fp_github_io); // maybe would work until Tue, 21 Mar 2023 23:59:59 GMT
  //client.setTrustAnchors(&cert_pem_first); // should work until Tue, 21 Mar 2023 23:59:59 GMT
  //client.setTrustAnchors(&cert_pem_second); // should work until Tue, 21 Mar 2023 23:59:59 GMT
  //client.setTrustAnchors(&cert_pem_third); // should work until Tue, 21 Mar 2023 23:59:59 GMT
  //client.setTrustAnchors(&cert); // should work until 2031-04-13 23:59:59
  client.setTrustAnchors(&cert_pem); // should work until Fri, 14 Mar 2025 23:59:59 GMT
#elif defined (ESP32)
  client.setCACert(cert_DigiCert_TLS_RSA_SHA256_2020_CA1);
#endif
  if (!client.connect(host, httpsPort))
  {
    Serial.println("connection failed");
    return;
  }
  Serial.print("requesting URL: ");
  Serial.println(String("https://") + host + path + filename);
  client.print(String("GET ") + path + filename + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "User-Agent: GxEPD2_WiFi_CertStore_Loader\r\n" +
               "Connection: close\r\n\r\n");
  Serial.println("request sent");
  bool ok = false;
  while (client.connected() || client.available())
  {
    String line = client.readStringUntil('\n');
    if (!ok)
    {
      ok = line.startsWith("HTTP/1.1 200 OK");
      if (ok) Serial.println(line);
      //if (!ok) Serial.println(line);
    }
    if (!ok) Serial.println(line);
    //Serial.println(line);
    if (line == "\r")
    {
      Serial.println("headers received");
      break;
    }
  }
  if (!ok) return;
  uint8_t buffer[512];
  size_t total = 0;
#if defined (ESP8266)
  fs::File file = LittleFS.open(target, "w+");
#elif defined(ESP32)
  fs::File file = SPIFFS.open(String("/") + target, "w+");
#endif
  if (!file)
  {
    Serial.print(target); Serial.println(" open failed");
    return;
  }
  while (client.connected() || client.available())
  {
    // this doesn't work as expected, but it helps for long downloads
    int32_t start = millis();
    for (int16_t t = 0, dly = 50; t < 20; t++, dly += 50)
    {
      if (!(client.connected() || client.available())) break;
      if (client.available()) break; // read would not recover after having returned 0
      delay(dly);
    }
    if (!(client.connected() || client.available())) break;
    int32_t elapsed = millis() - start;
    if (elapsed > 250)
    {
      Serial.print("waited for available "); Serial.print(millis() - start); Serial.print(" ms @ "); Serial.println(total);
    }
    size_t available = client.available();
    if (0 == available)
    {
      Serial.print("download error: timeout on available() after "); Serial.print(total); Serial.println(" bytes");
      break; // don't hang forever
    }
    size_t fetch = available <= sizeof(buffer) ? available : sizeof(buffer);
    if (fetch > 0)
    {
      size_t got = client.read(buffer, fetch);
      file.write(buffer, got);
      total += got;
    }
    delay(1); // yield();
    if (total > 30000) delay(250); // helps for long downloads
  }
  file.close();
  Serial.print("done, "); Serial.print(total); Serial.println(" bytes transferred");
}

// Set time via NTP, as required for x.509 validation
void setClock() 
{
  configTime(3 * 3600, 0, "pool.ntp.org", "time.nist.gov");

  Serial.print("Waiting for NTP time sync: ");
  time_t now = time(nullptr);
  while (now < 8 * 3600 * 2) 
  {
    delay(500);
    Serial.print(".");
    now = time(nullptr);
  }
  Serial.println("");
  struct tm timeinfo;
  gmtime_r(&now, &timeinfo);
  Serial.print("Current time: ");
  Serial.print(asctime(&timeinfo));
}
