/*
 * SPDX-FileCopyrightText: Copyright (C) Frickly Systems GmbH
 * SPDX-FileCopyrightText: Copyright (C) MBition GmbH
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#include <zephyr/logging/log.h>
LOG_MODULE_REGISTER(firmware_loader, CONFIG_APP_LOG_LEVEL);

#include <zephyr/device.h>
#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include <zephyr/retention/retention.h>

#include <ardep/iso14229.h>
#include <ardep/uds.h>

const struct device *retention_data =
    DEVICE_DT_GET(DT_CHOSEN(zephyr_firmware_loader_args));

const struct device *can_dev = DEVICE_DT_GET(DT_CHOSEN(zephyr_canbus));

int main() {
  LOG_INF("Hello firmware-loader");

  // load stored session type
  uint8_t session_type;
  int ret = retention_read(retention_data, 0, &session_type, 1);
  if (ret != 0) {
    LOG_ERR("Failed to read from retention 1: %d", ret);
    return ret;
  }
  LOG_INF("Read stored session type from retention data: %02x", session_type);

  // reset session type in storage to prevent reboot-loops
  const uint8_t reset_session_type = UDS_DIAG_SESSION__DEFAULT;
  ret = retention_write(retention_data, 0, &reset_session_type, 1);
  if (ret != 0) {
    LOG_ERR("Failed to write to retention 1: %d", ret);
    return ret;
  }

  if (session_type == UDS_DIAG_SESSION__PROGRAMMING) {
    LOG_INF("Injecting DiagnosticSessionControl (Programming) frame");
    struct can_frame frame = {
      .id = 0,  // overwritten by iso14229_inject_can_frame_rx
      .dlc = 3,
      .flags = 0,
    };
    frame.data[0] = 0x02;  // PCI (single frame, 2 bytes of data)
    frame.data[1] = 0x10;  // SID (DiagnosticSessionControl)
    frame.data[2] = 0x02;  // DS  (Programming Session)

    iso14229_inject_can_frame_rx(&uds_default_instance.iso14229, &frame, false);
  }

  return 0;
}
