/**
 * @file main.c
 * @brief Main routine
 *
 * @section License
 *
 * Copyright (C) 2021-2026 Oryx Embedded SARL. All rights reserved.
 * 
 * SPDX-License-Identifier: GPL-2.0-or-later
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

 *
 * @author Oryx Embedded SARL (www.oryx-embedded.com)
 * @version 2.6.4
 **/

//Dependencies
#include <stdlib.h>
#include "stm32l4xx.h"
#include "stm32l4xx_hal.h"
#include "stm32l4xx_nucleo.h"
#include "os_port.h"
#include "boot_config.h"
#include "drivers/flash/internal/stm32l4xx_flash_driver.h"
#include "first_stage/boot.h"
#include "core/mailbox.h"
#include "debug.h"

#define SECOND_STAGE_ADDR  0x08008000
#define BOOT_OFFSET        0x0

uint8_t ledState = 0;
systime_t ledDelay = 0;
systime_t ledTimestamp = 0;

#define SLOT_COUNT 2

uint32_t available_slots[SLOT_COUNT] = {
	0x08030000,
	0x08050000
};

/**
  * @brief  System Clock Configuration
  *         The system Clock is configured as follows :
  *            System Clock source            = PLL (MSI)
  *            SYSCLK(Hz)                     = 80000000
  *            HCLK(Hz)                       = 80000000
  *            AHB Prescaler                  = 1
  *            APB1 Prescaler                 = 1
  *            APB2 Prescaler                 = 1
  *            MSI Frequency(Hz)              = 4000000
  *            PLL_M                          = 1
  *            PLL_N                          = 40
  *            PLL_R                          = 2
  *            PLL_P                          = 7
  *            PLL_Q                          = 4
  *            Flash Latency(WS)              = 4
  * @param  None
  * @retval None
  */
void SystemClock_Config(void) {
	RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
	RCC_OscInitTypeDef RCC_OscInitStruct = {0};

	/* MSI is enabled after System reset, activate PLL with MSI as source */
	RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI;
	RCC_OscInitStruct.MSIState = RCC_MSI_ON;
	RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_6;
	RCC_OscInitStruct.MSICalibrationValue = RCC_MSICALIBRATION_DEFAULT;
	RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
	RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_MSI;
	RCC_OscInitStruct.PLL.PLLM = 1;
	RCC_OscInitStruct.PLL.PLLN = 40;
	RCC_OscInitStruct.PLL.PLLR = 2;
	RCC_OscInitStruct.PLL.PLLP = 7;
	RCC_OscInitStruct.PLL.PLLQ = 4;
	if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
		/* Initialization Error */
		while (1);
	}

	/* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2
	   clocks dividers */
	RCC_ClkInitStruct.ClockType = (
		RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2);
	RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
	RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
	RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
	RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
	if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK) {
		/* Initialization Error */
		while (1);
	}
}


/**
 * @brief LED task
 * @param[in] param Unused parameter
 **/

void ledTask() {
	if ((uint32_t) (systemTicks - ledTimestamp) >= ledDelay) {
		//Toggle LED state
		if (ledState == 0) {
			BSP_LED_On(LED2);
			ledState = 1;
			ledDelay = 100;
		} else {
			BSP_LED_Off(LED2);
			ledState = 0;
			ledDelay = 900;
		}

		ledTimestamp = systemTicks;
	}
}


/**
 * @brief Main entry point
 * @return Unused value
 **/

int_t main(void) {
	BootContext context;

	cboot_error_t cerror;

	//HAL library initialization
	HAL_Init();
	//Configure the system clock
	SystemClock_Config();
	//Initialize kernel
	osInitKernel();
	//Configure debug UART
	debugInit(115200);

	//Start-up message
	TRACE_INFO("\r\n");
	TRACE_INFO("******************************************\r\n");
	TRACE_INFO("*** CycloneBOOT First Stage Bootloader ***\r\n");
	TRACE_INFO("******************************************\r\n");
	TRACE_INFO("Copyright: 2010-2025 Oryx Embedded SARL\r\n");
	TRACE_INFO("Compiled: %s %s\r\n", __DATE__, __TIME__);
	TRACE_INFO("Target: STM32L476\r\n");
	TRACE_INFO("\r\n");

	//LED configuration
	BSP_LED_Init(LED2);

	//Clear LEDs
	BSP_LED_Off(LED2);

	mailBoxInit();

	//Begining of handling exception
	do {
		cerror = CBOOT_NO_ERROR;

		context.bl_address = SECOND_STAGE_ADDR;
		context.driver = &stm32l4xxFlashDriver;
		context.offset = BOOT_OFFSET;
		context.slot_count = SLOT_COUNT;
		context.slots = available_slots;

		cerror = bootFsm(&context);
		if (cerror != CBOOT_NO_ERROR) {
			TRACE_ERROR("Something went wrong.\r\n");
			bootHandleError();
			break;
			//TODO: hook here?
		}
	} while (0);

	//Is any error?
	if (cerror) {
		//Debug message
		TRACE_ERROR("Bootloader configuration failed!\r\n");
	}

	__HAL_FLASH_SET_LATENCY(FLASH_LATENCY_4);

	while (1) {
		ledTask();
	}

	//This function should never return
	return 0;
}

void bootHandleError(void) {
	/*
	 * This function will be called when the bootloader encounters a generic error
	 * state. It can be redefined in user code.
	 */
	TRACE_ERROR("In bootHandleError\r\n");
}
