/**
 * @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 "stm32u5xx.h"
#include "stm32u5xx_hal.h"
#include "stm32u5xx_nucleo.h"
#include "os_port.h"
#include "drivers/flash/internal/stm32u5xx_flash_driver.h"
#include "image/image.h"
#include "second_stage/boot.h"
#include "memory/memory.h"
#include "debug.h"
#include "second_stage/boot_fallback.h"

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

/**
 * @brief System clock configuration
 **/

void SystemClock_Config(void) {
	RCC_OscInitTypeDef RCC_OscInitStruct = {0};
	RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
	RCC_PeriphCLKInitTypeDef RCC_PeriphClkInitStruct = {0};

	//Enable voltage range 1 for frequency above 100 MHz
	__HAL_RCC_PWR_CLK_ENABLE();
	HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1);
	__HAL_RCC_PWR_CLK_DISABLE();

	//Configure PLL with MSI as source
	RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI48 | RCC_OSCILLATORTYPE_MSI;
	RCC_OscInitStruct.HSI48State = RCC_HSI48_ON;
	RCC_OscInitStruct.MSIState = RCC_MSI_ON;
	RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_4;
	RCC_OscInitStruct.MSICalibrationValue = RCC_MSICALIBRATION_DEFAULT;
	RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
	RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_MSI;
	RCC_OscInitStruct.PLL.PLLMBOOST = RCC_PLLMBOOST_DIV1;
	RCC_OscInitStruct.PLL.PLLM = 1;
	RCC_OscInitStruct.PLL.PLLN = 80;
	RCC_OscInitStruct.PLL.PLLR = 2;
	RCC_OscInitStruct.PLL.PLLP = 2;
	RCC_OscInitStruct.PLL.PLLQ = 2;
	RCC_OscInitStruct.PLL.PLLFRACN = 0;
	HAL_RCC_OscConfig(&RCC_OscInitStruct);

	//Select PLL as system clock source and configure bus clocks dividers
	RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK |
	                              RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2 | RCC_CLOCKTYPE_PCLK3;
	RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
	RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
	RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
	RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
	RCC_ClkInitStruct.APB3CLKDivider = RCC_HCLK_DIV1;
	HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4);

	//Select clock source for RNG peripheral
	RCC_PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RNG;
	RCC_PeriphClkInitStruct.RngClockSelection = RCC_RNGCLKSOURCE_HSI48;
	HAL_RCCEx_PeriphCLKConfig(&RCC_PeriphClkInitStruct);
}

/**
 * @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(LED1);
			ledState = 1;
			ledDelay = 100;
		} else {
			BSP_LED_Off(LED1);
			ledState = 0;
			ledDelay = 900;
		}

		ledTimestamp = systemTicks;
	}
}


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

int_t main(void) {
	BootSettings bootSettings;
	BootContext bootContext;

	cboot_error_t cerror;

	//HAL library initialization
	HAL_Init();
	//Configure the system clock
	SystemClock_Config();

	//Enable instruction cache
	HAL_ICACHE_ConfigAssociativityMode(ICACHE_2WAYS);
	HAL_ICACHE_Enable();

	//Initialize kernel
	osInitKernel();
	//Configure debug UART
	debugInit(115200);

	//Start-up message
	TRACE_INFO("\r\n");
	TRACE_INFO("******************************************\r\n");
	TRACE_INFO("*** CycloneBOOT Single Bank Bootloader ***\r\n");
	TRACE_INFO("******************************************\r\n");
	TRACE_INFO("Copyright: 2010-2026 Oryx Embedded SARL\r\n");
	TRACE_INFO("Compiled: %s %s\r\n", __DATE__, __TIME__);
	TRACE_INFO("Target: STM32U575\r\n");
	TRACE_INFO("\r\n");

	//LED configuration
	BSP_LED_Init(LED1);
	BSP_LED_Init(LED2);
	BSP_LED_Init(LED3);

	//Clear LEDs
	BSP_LED_Off(LED1);
	BSP_LED_Off(LED2);
	BSP_LED_Off(LED3);

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

		//Get default booloader user settings
		bootGetDefaultSettings(&bootSettings);

		//User settings primary memory configuration
		bootSettings.memories[0].memoryType = MEMORY_TYPE_FLASH;
		bootSettings.memories[0].memoryRole = MEMORY_ROLE_PRIMARY;
		bootSettings.memories[0].driver = &stm32u5xxFlashDriver;
		bootSettings.memories[0].nbSlots = 3;
		//User settings primary memory slot 0 configuration
		bootSettings.memories[0].slots[0].type = SLOT_TYPE_DIRECT;
		bootSettings.memories[0].slots[0].cType = SLOT_CONTENT_APP;
		bootSettings.memories[0].slots[0].memParent = &bootSettings.memories[0];
		bootSettings.memories[0].slots[0].addr = 0x08020000;
		bootSettings.memories[0].slots[0].size = 0x7D000;
		//User settings primary memory slot 1 configuration
		bootSettings.memories[0].slots[1].type = SLOT_TYPE_DIRECT;
		bootSettings.memories[0].slots[1].cType = SLOT_CONTENT_UPDATE | SLOT_CONTENT_BACKUP;
		bootSettings.memories[0].slots[1].memParent = &bootSettings.memories[0];
		bootSettings.memories[0].slots[1].addr = 0x080C0000;
		bootSettings.memories[0].slots[1].size = 0x7D000;
		//User settings primary memory slot 2 configuration
		bootSettings.memories[0].slots[2].type = SLOT_TYPE_DIRECT;
		bootSettings.memories[0].slots[2].cType = SLOT_CONTENT_UPDATE | SLOT_CONTENT_BACKUP;
		bootSettings.memories[0].slots[2].memParent = &bootSettings.memories[0];
		bootSettings.memories[0].slots[2].addr = 0x08160000;
		bootSettings.memories[0].slots[2].size = 0x7D000;

		//Initialize bootloader
		cerror = bootInit(&bootContext, &bootSettings);
		//Is any error?
		if (cerror)
			break;
	} while (0);

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

	while (1) {
		ledTask();
		cerror = bootFsm(&bootContext);
		//Is any error?
		if (cerror) {
			//Debug message
			TRACE_ERROR("Bootloader failure!\r\n");
		}
	}

	//This function should never return
	return 0;
}


cboot_error_t fallbackTriggerInit(void)
{
	// This function Should not be modified when the callback is needed,
	//  the fallbackTriggerInit must be implemented in the user file
	BSP_PB_Init(BUTTON_USER, BUTTON_MODE_GPIO);
	return CBOOT_NO_ERROR;
}

/**
 * @brief Fallback Trigger Status callback.
 * It is declared week and must be declared in user codde space.
 * @param[in] status Trigger status to be returned (Raised or Idle)
 * @return Status Code
 **/

cboot_error_t fallbackTriggerGetStatus(TriggerStatus *status)
{
	// This function Should not be modified when the callback is needed,
	// the fallbackTriggerGetStatus must be implemented in the user file
	if (BSP_PB_GetState(BUTTON_USER) == GPIO_PIN_SET) {
		HAL_Delay(200);
		if (BSP_PB_GetState(BUTTON_USER) == GPIO_PIN_SET) {
			*status = TRIGGER_STATUS_RAISED;
		} else {
			*status = TRIGGER_STATUS_IDLE;
		}
	} else {
		*status = TRIGGER_STATUS_IDLE;
	}

	return CBOOT_NO_ERROR;
}