#/bin/bash
# At this stage, we can consider the new image has successfully boot, so the bootcount can be disabled.
# To disable it, "accepted" entry has to be true in metadata (in order to leave trial mode)

arg1=$1
arg2=$2
arg3=$3

booted_system=""

get_booted_system()
{
    cat /proc/cmdline | grep "rauc.slot=system0" > /dev/null
    if test $? == 0
    then
        booted_system="system0"
    else
        booted_system="system1"
    fi
}

# return the booted system
if [ "$arg1" = "get-primary" ]
then
    get_booted_system
    echo "$booted_system"
    exit 0
fi

# consider every boot system as good
if [ "$arg1" = "get-state" ]
then
    echo "good"
    exit 0
fi

# When boot succeeded, the rauc mark-good service is executed which
# enters in this function.
# Also handle the mark-bad service.
if [ "$arg1" = "set-state" ]
then
    if [ "$arg3" = "bad" ]
    then
        get_booted_system
        if [ "$arg2" = "system0" ] && [ "$booted_system" = "system0" ]
        then
            /usr/lib/fwu/update_metadata.sh 1 0 refuse > /dev/null
        elif [ "$arg2" = "system1" ] && [ "$booted_system" = "system1" ]
        then
            /usr/lib/fwu/update_metadata.sh 0 1 refuse > /dev/null
        fi
    else
        if [ "$arg2" = "system0" ]
        then
            /usr/lib/fwu/update_metadata.sh 0 0 accept > /dev/null
        else
            /usr/lib/fwu/update_metadata.sh 1 1 accept > /dev/null
        fi
    fi
    exit 0
fi

# Handle the rauc mark-active service
if [ "$arg1" = "set-primary" ]
then
    get_booted_system
    if [ "$arg2" = "system0" ] && [ "$booted_system" = "system1" ]
    then
        /usr/lib/fwu/update_metadata.sh 0 1 refuse > /dev/null
    elif [ "$arg2" = "system1" ] &&  [ "$booted_system" = "system0" ]
    then
        /usr/lib/fwu/update_metadata.sh 1 0 refuse > /dev/null
    fi
    exit 0
fi
