#!/bin/sh
# collect-yocto-context.sh: a few facts about a kirkstone build for PatchProvenance, and
# nothing else. Optional. Our report tool reads its output with your cve-check file: it compares
# the commit with the OE-core revision our patches were judged on, and, for recipes your
# cve-check file names as OE-core's, where our build rules tie the files a fix changes to a
# PACKAGECONFIG option, checks PACKAGECONFIG to mark the CVEs whose fixed code your
# configuration leaves out. Nothing else of ours reads it.
#
# Run it inside an initialised build environment, after `source oe-init-build-env`:
#
#     sh collect-yocto-context.sh > yocto-context.json
#
# It writes one JSON document to standard output with:
#   - the commit of the checkout COREBASE points to (OE-core itself, or poky, which carries
#     it), only when COREBASE is the top of that checkout; and DISTRO_VERSION;
#   - for each of the 25 recipes listed below: PV and the resolved PACKAGECONFIG.
#
# It reads only those variables, with bitbake-getvar and git. It makes no network request and
# asks bitbake not to make one (BB_NO_NETWORK=1, and BB_SRCREV_POLICY=cache, so that a recipe
# with AUTOREV takes the revision of your last build), writes no file of its own (bitbake keeps
# its usual cache in the build directory), and prints no path, user name, host name, URL,
# password or source code. A value with any character outside A-Z a-z 0-9 . _ + ~ - and space
# is left out, and its name is listed under "dropped"; so is a PACKAGECONFIG or DISTRO_VERSION
# that bitbake-getvar could not give (it ended with an error). A recipe whose PV it cannot give
# is written as null, and a COREBASE it cannot give leaves the commit empty. Read the output
# before you send it: it is short.
#
# Check this script before you run it: read it, and check it against the SHA-256 shown next
# to the download on https://patchprovenance.com/#check
#
#     echo "<SHA-256>  collect-yocto-context.sh" | sha256sum -c
#
# Asking bitbake for about 50 values takes a few minutes.

set -eu

RECIPES="openssl curl busybox zlib expat libxml2 dropbear openssh glibc libpng libjpeg-turbo
sqlite3 e2fsprogs util-linux bash ncurses libarchive wpa-supplicant bluez5 dbus systemd gnutls
nghttp2 tiff freetype"

if ! command -v bitbake-getvar >/dev/null 2>&1; then
    echo "bitbake-getvar not found: run this inside the build environment (source oe-init-build-env)" >&2
    exit 1
fi

NL="
"
DROPPED=""

# Set VALUE to the value of one variable, global or of one recipe, and FAILED to 1 when
# bitbake-getvar ended with an error (VALUE is then empty, and the value unknown, not empty).
# bitbake may log lines before the value, so only the last line counts. The "." after it
# keeps that line when the value is empty. bitbake prints None for a variable that is not set.
# (Called directly, not in $( ), so that FAILED survives.)
getvar() {
    FAILED=0
    if [ -n "$2" ]; then
        out=$(BB_NO_NETWORK=1 BB_SRCREV_POLICY=cache \
            bitbake-getvar -r "$2" --value "$1" 2>/dev/null && echo .) || FAILED=1
    else
        out=$(BB_NO_NETWORK=1 BB_SRCREV_POLICY=cache \
            bitbake-getvar --value "$1" 2>/dev/null && echo .) || FAILED=1
    fi
    if [ "$FAILED" -eq 1 ]; then
        out=""
    fi
    out=${out%.}
    out=${out%"$NL"}
    out=${out##*"$NL"}
    if [ "$out" = "None" ]; then
        out=""
    fi
    VALUE=$out
}

# Set CLEAN to the value when it is made only of the allowed characters; otherwise set it
# empty and note the name under "dropped". Allowed values never need escaping in JSON.
# (Called directly, not in $( ), so that DROPPED survives.)
clean() {
    CLEAN=""
    case "$2" in
        *[!A-Za-z0-9._+~\ -]*)
            DROPPED="$DROPPED $1"
            return 0
            ;;
    esac
    CLEAN=$2
}

field() {
    printf '"%s": "%s"' "$1" "$2"
}

getvar COREBASE ""
corebase=$VALUE
revision=""
# Only when COREBASE is the top of its own checkout: inside another repository, HEAD would be
# a commit of that repository, not of OE-core.
if [ -n "$corebase" ] && [ -d "$corebase" ] &&
    [ -z "$(git -C "$corebase" rev-parse --show-prefix 2>/dev/null || echo outside)" ]; then
    revision=$(git -C "$corebase" rev-parse HEAD 2>/dev/null || true)
fi
case "$revision" in
    *[!0-9a-f]* | "") revision="" ;;
esac
getvar DISTRO_VERSION ""
if [ "$FAILED" -eq 1 ]; then
    DROPPED="$DROPPED DISTRO_VERSION"
    distro=""
else
    clean DISTRO_VERSION "$VALUE"
    distro=$CLEAN
fi

printf '{\n  "tool": "collect-yocto-context",\n  "format": 1,\n'
printf '  %s,\n' "$(field corebase_revision "$revision")"
printf '  %s,\n' "$(field distro_version "$distro")"
printf '  "recipes": {'
separator="
"
found=0
for recipe in $RECIPES; do
    getvar PV "$recipe"
    pv=$VALUE
    printf '%s    "%s": ' "$separator" "$recipe"
    separator=",
"
    if [ -z "$pv" ]; then
        printf 'null'
        continue
    fi
    found=$((found + 1))
    clean "$recipe:PV" "$pv"
    pv=$CLEAN
    getvar PACKAGECONFIG "$recipe"
    if [ "$FAILED" -eq 1 ]; then
        DROPPED="$DROPPED $recipe:PACKAGECONFIG"
        packageconfig=""
    else
        clean "$recipe:PACKAGECONFIG" "$VALUE"
        packageconfig=$CLEAN
    fi
    printf '{%s, %s}' "$(field pv "$pv")" "$(field packageconfig "$packageconfig")"
done
printf '\n  },\n  "dropped": ['
separator=""
for name in $DROPPED; do
    printf '%s"%s"' "$separator" "$name"
    separator=", "
done
printf ']\n}\n'

if [ "$found" -eq 0 ]; then
    echo "bitbake gave no value for any recipe. Run this in an initialised build environment, after a build: with BB_NO_NETWORK=1 bitbake cannot parse a recipe whose SRCREV is AUTOREV, a tag or a branch unless that build stored its revision." >&2
fi
