#!/bin/sh
#
#  u-boot-mkimage - preinstall script which removes u-boot image header
#
#  Copyright (C) 2020 Cumulus Networks, Inc. All rights reserved
#
#  This software is subject to the Cumulus Networks End User License
#  Agreement available at the following locations:
#
#  Internet: https://cumulusnetworks.com/downloads/eula/latest/view/
#
#  Cumulus Linux systems: /usr/share/cumulus/EULA.txt
#

set -e

# Determine if UBIFS is in use by looking at sysfs nodes
ubifs_in_use()
{
    local ubifs

    for ubifs in /sys/class/ubi/ubi?/ubi?_?
    do
        [ -d "${ubifs}" ] && return 0 || return 1
    done
}

# Look for the first four bytes of image equal to magic value
has_image_header()
{
    local image="${1}"
    local magic=$(head -c 4 ${image})

    if [ "${magic}" = $'\x27\x05\x19\x56' ]
    then
        return 0
    fi
    return 1
}

# Remove the first 64 bytes from a file
remove_image_header()
{
    local image="${1}"
    local backup=$(mktemp)

    tail -c +64 ${image} > ${backup}
    mv ${backup} ${image}
}

# Make sure kernel image exists
[ -r "${2}" ] || {
    echo "Error: kernel image (${2}) does not exist" >&2
    exit 1
}

if ubifs_in_use
then
    if has_image_header "${2}"
    then
        remove_image_header "${2}"
    fi
fi

# end of file
