#!/usr/bin/ash
# shellcheck shell=dash
# archiso provides the mount handler, source drive, architecture and copy-to-RAM policy.
# shellcheck disable=SC2154
starchaser_integrity_stop() {
    echo "Secure Boot: $1"
    poweroff -f
    # A damaged live root must never become an unauthenticated emergency shell.
    while :; do sleep 60; done
}

starchaser_verify_image() {
    local image="$1" expected actual
    expected=$(getarg starchaser.live-sha256)
    [ -n "$expected" ] || return 0
    actual=$(sha256sum "$image") || starchaser_integrity_stop 'The live system could not be verified. Make a new signed stick.'
    [ "${actual%% *}" = "$expected" ] || starchaser_integrity_stop 'The live system was changed or damaged. Make a new signed stick.'
}

run_hook() {
    [ -n "$(getarg starchaser.live-sha256)" ] || return 0
    [ "$mount_handler" = archiso_mount_handler ] || starchaser_integrity_stop 'Write this signed image directly to a USB stick before starting it.'
    mount_handler=starchaser_verified_mount
}

starchaser_verified_mount() {
    case "$archisobasedir/$arch" in *..*) starchaser_integrity_stop 'The signed recovery path is invalid.' ;; esac
    if [ -n "$archisosearchfilename" ]; then _search_for_archisodevice; fi
    if ! mountpoint -q /run/archiso/bootmnt; then
        _mnt_dev "$archisodevice" /run/archiso/bootmnt -r defaults
    fi
    starchaser_verify_image "/run/archiso/bootmnt/$archisobasedir/$arch/airootfs.sfs"
    archiso_mount_handler "$1"
}

run_latehook() {
    [ -n "$(getarg starchaser.live-sha256)" ] || return 0
    if [ "$copytoram" = y ]; then
        starchaser_verify_image /run/archiso/copytoram/airootfs.sfs
    else
        starchaser_verify_image "/run/archiso/bootmnt/$archisobasedir/$arch/airootfs.sfs"
    fi
}
