#!/bin/sh

RCINIT=/usr/share/resources/default/init/main

# Load resources
[ -f "$RCINIT" ] && . "$RCINIT"

LDRENV_MPT=/var/lib/spinetix/ldrenv

function show_usage()
{
    echo "usage: {write <value> | read}" >&2
}

function do_plain_file_bootcount()
{
    local bootcount="$rc_bootcount_path"
    local op="$1"
    local val="$2"

    [ -n "$rc_bootcount_path" ] || bootcount=/proc/driver/bootcount
    if ! [ -f "$bootcount" ]; then
        echo "ERROR: bootcount file '$bootcount' does not exist" >&2
        return 1
    fi
    case "$op" in
        write)
            echo "$val" > "$bootcount"
            ;;
        read)
            cat "$bootcount"
            ;;
        *)
            show_usage >&2
            return 1
            ;;
    esac
}

function do_grub_env_block_bootcount()
{
    local op="$1"
    local val="$2"
    local envfile="$LDRENV_MPT"/"$rc_bootcount_path"
    local values=

    case "$op" in
        write)
            grub-editenv "$envfile" set bootcount="$val"
            ;;
        read)
            # NOTE: grub-editenv list will create the file if it does not exist
            if ! [ -s "$envfile" ]; then
                echo "ERROR: bootcount environment block file does not exist or empty" >&2
                return 1
            fi
            values="$(grub-editenv "$envfile" list)" || return
            echo "$values" | sed -n -e '/^bootcount=/{s/^[^=]*=//;p;q;}'
            ;;
        *)
            show_usage >&2
            return 1
            ;;
    esac
}

function do_none_bootcount()
{
    local op="$1"
    local val="$2"
    case "$op" in
        write)
            # ignore write with success
            return 0
            ;;
        read)
            # always zero
            echo 0
            ;;
        *)
            show_usage >&2
            return 1
            ;;
    esac
}

case "$rc_bootcount_style" in
    plain-file|'') # for backwards compat an empty style is the same as this one
        do_plain_file_bootcount "$@"
        ;;
    grub-env-block)
        do_grub_env_block_bootcount "$@"
        ;;
    none)
        do_none_bootcount "$@"
        ;;
    *)
        echo "ERROR: unknown bootcount style '$rc_bootcount_style'" >&2
        ;;
esac
