#!/bin/sh

set -e

kversion="$1"
initrd="$2"

# Disable if our package is not installed.
if ! command -v depthchargectl >/dev/null 2>&1; then
    echo "Not writing depthcharge image, depthchargectl is missing." >&2
    exit 0
fi

# Ignore errors if we're not booted with depthcharge
maybe_error() {
    if grep "cros_secure" /proc/cmdline >/dev/null 2>&1; then
        echo "Failed to write depthcharge image, system may be unbootable." >&2
        exit 1
    else
        echo "Not booted with depthcharge, so ignoring that." >&2
        exit 0
    fi
}

# Disable based on package configuration
enabled="$(
    depthchargectl config \
        --section depthchargectl/write \
        --default False \
        enable-system-hooks
)" || maybe_error
if [ "$enabled" != "True" ]; then
    echo "Not writing depthcharge image, disabled by config." >&2
    exit 0
fi

board="$(depthchargectl config board)" || maybe_error
if [ "$board" = "none" ]; then
    echo "Cannot build depthcharge images when no board is specified." >&2
    maybe_error
fi

count="$(depthchargectl list -c)" || maybe_error
if [ "$count" -gt 1 ]; then
    echo "Running depthchargectl write '$kversion':" >&2
    depthchargectl write "$kversion" >/dev/null \
        || maybe_error

elif [ "$count" -eq 1 ]; then
    echo "Running depthchargectl write --allow-current '$kversion':" >&2
    depthchargectl write --allow-current "$kversion" >/dev/null \
        || maybe_error

else
    echo "No usable Chrome OS Kernel partition found." >&2
    maybe_error
fi
