#!/bin/sh
#
#  u-boot-mkimage - postupdate script which adds 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}
}

# Add an image header
add_image_header()
{
    local image="${1}"
    local backup=$(mktemp)

    mv ${image} ${backup}
    mkimage \
        -A arm \
        -O linux \
        -T ramdisk \
        -C none \
        -n Cumulus_Initrd \
        -d ${backup} ${image} > /dev/null
    if [ $? -eq 0 ]
    then
        rm ${backup}
    else
        echo "Error: Count not add header to initramfs image (${image})" >&2
        mv ${backup} ${image}
        return 1
    fi
}

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

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

# end of file
