UPGRADE_FW_MAJOR="2022-09-13-0-11012d53-22.08-plus"
UPGRADE_FW_VERSION="2024-03-26-0-5aa91fcb-24.03-plus"
UPGRADE_FW_REQUIRE="2022-09-13-0-11012d53-22.08-plus"

current_fw_version() {
    cat /etc/bos_version
}

current_fw_major() {
    cat /etc/bos_major
}

check_fw_version() {
    echo "Gathering current firmware information..."

    local fw_major=$(current_fw_major)
    local fw_version=$(current_fw_version)

    echo "version             : $fw_version"
    echo "major               : $fw_major"

    echo "Checking compatibility..."

    if [ "$UPGRADE_FW_VERSION" ">" "$fw_version" ]; then
        # firmware upgrade
        if [ "$UPGRADE_FW_REQUIRE" ">" "$fw_version" ]; then
            echo "Firmware upgrade to '$UPGRADE_FW_VERSION' is not possible!"
            echo "Firmware version '$UPGRADE_FW_REQUIRE' is required before upgrading to this version."
            return 1
        fi
    elif [ "$UPGRADE_FW_VERSION" "<" "$fw_version" ]; then
        # firmware downgrade
        if [ "$UPGRADE_FW_MAJOR" != "$fw_major" ]; then
            echo "Firmware downgrade to '$UPGRADE_FW_VERSION' is not possible!"
            echo "Downgrade is only possible among firmwares with major version '$UPGRADE_FW_MAJOR'."
            echo "Do the factory reset and try to upgrade to this version."
            return 1
        fi
    fi

    return 0
}

check_image() {
    check_fw_version
}

do_upgrade() {
    local image_file="$1"

    . /lib/functions/common.sh
    local bos_mount_image_path="${BOS_INSTALL_MOUNT_PATH}/${BOS_ROOTFS_FILE}"

    # Move the file so it will not fill up the /tmp
    mv "$image_file" "$bos_mount_image_path"

    # Reboot will start `restart` action of `bos-runner.sh`
    # where the BOS unmounts and run again standard way
    # running `/nvdata/bos/bos-run.sh`. So `bos-runner.sh`, `common.sh`,
    # `bos-tools` is updated from new image. But only action `run` is
    # executed with new version, action `restart` is run with old.
    reboot
    exit 0
}
