#!/bin/bash
#Wrapper for file signature generation, meant to be used by binman

#Expect sign key info to be provided via env. We could provide everything through
#binman in *u-boot.dtsi, but we'd need to add specific preprocessor definitions
#for these variables because we are surely not hardcoding these. 
#Also we expose paths in compiled DTB if we define in .dtsi, not ideal.
#These should always be defined by the main Makefile if we are using signature checks.

#check if vars were not defined, then skip this sign step completely
[ -n "${FIT_KEY_ALG+x}" ] || [ -n "${FIT_PRIV_KEY+x}" ] || [ -n "${VERIFIED_BOOT_LOCAL_SIGN+x}" ] || exit 2

#Arguments from binman
[ $# -ne 2 ] && exit 1
DATA=$1
OUTFILE=$2

#now whether do to local sign, or external sign
[ "$VERIFIED_BOOT_LOCAL_SIGN" = "" ] && {
    # tool was not provided
    # it should accept:
    #   sign key or some id (tool manages it's own keys)
    #   data file for sign
    #   signature file name
    [ -n "${FIT_SIGNER_TOOL+x}" ] || exit 1

    "$FIT_SIGNER_TOOL" "boot?key=$FIT_PRIV_KEY" "$DATA" "$OUTFILE"
    exit $?
}

EXTS=".key .priv"
PKEY=""
for ext in $EXTS; do
    [ -f "$FIT_PRIV_KEY""$ext" ] && {
        PKEY="$FIT_PRIV_KEY""$ext"
        break
    }
done

[ "$PKEY" = "" ] && exit 1

# we are doing local sign, use host openssl
which openssl >> /dev/null || exit 1

[ -f "$DATA" ] || exit 1

HASH_ALG=$(echo "$FIT_KEY_ALG" | cut -d ',' -f1)

echo "Sign $HASH_ALG of $DATA, output: $OUTFILE"
openssl dgst -$HASH_ALG -sign "$PKEY" -binary -out "$OUTFILE" "$DATA"