#!/usr/bin/python

'''
The role of this script is to check if all RL78s have, at least, the minimal firmware version according to the actual OS version
The RL78s that don't match minimal firmware version will be automatically updated
'''

import sys
sys.path.append('/home/root/SeaCloudScripts')
sys.path.append('/tmp/update')  # needed for update type detection
import logging
import lib_logger
import lib_RL78
import lib_system               # needed for update type check

# Folder where the RL78 firmware file is stored
RL78_FIRMWARE_FOLDER = "/backup"

# Return values of the function get_RL78_file_path_from_image
NO_ERROR = 0
ERROR_FILENAME = 1

logger = logging.getLogger()

if __name__ == '__main__':

    tag_name = "RL78Updater"
    lib_logger.add_handler_stdout(tag_name)

    logger.info("Start RL78 firmware update")

    success = True
    logger.info("Release RL78 for update")
    lib_RL78.release_rl78s();

    update_type = lib_system.get_update_type()

    if update_type == "mcb":
        RL78_FIRMWARE_FOLDER = "/tmp/rootfs/backup"

    # Get fw file from the OS, exit gracefully if we are not able to get it
    yyx815_firmware_file_path = lib_RL78.get_rl78_firmware_file_path_from_folder(RL78_FIRMWARE_FOLDER, "YYX815")
    yyx844_firmware_file_path = lib_RL78.get_rl78_firmware_file_path_from_folder(RL78_FIRMWARE_FOLDER, "YYX844")

    logger.info("yyx815_firmware_file_path={}".format(yyx815_firmware_file_path))
    logger.info("yyx844_firmware_file_path={}".format(yyx844_firmware_file_path))
    logger.info("update_type={}".format(update_type))


    if yyx815_firmware_file_path == "" and yyx844_firmware_file_path == "":
        logger.error("Unable to retrieve RL78 firmware filename")
    elif update_type == "mcb" and yyx844_firmware_file_path == "":
        logger.error("Could not retrieve YYX844 RL78 firmware file needed for MCB update")
    elif update_type == "seacloud" and yyx815_firmware_file_path == "":
        logger.error("Could not retrieve YYX815 RL78 firmware file needed for Seacloud update")
    else:
        # Update the RLs that need to. Returns True if all the connected RLs have the good version at the exit (updated or not)
        success = lib_RL78.update_updatable_rl78s(yyx844_firmware_file_path, yyx815_firmware_file_path)

        if update_type == "mcb" and yyx815_firmware_file_path == "":
            logger.error("Incomplete MCB update, yyx815 missing")

        # Exit/Reboot. Reboot is needed if we came from a firmware update and we can not guarantee that all RL78s have the minimal firmware version
        if success:
            logger.info("Update successful")
        else:
            logger.error("Update failed.")

    logging.shutdown()
    exit(not success)

