#!/bin/sh
# Display/Test live system state
# 
# By default, the following information will be displayed:
#     bootmedia:  media system booted from, eg. cdr | usb
#     rootfs: live root filesystem running from, eg. ram | bootmedia
# 
# Arguments:
#     bootmedia[=cdr|usb]
#     rootfs[=ram|bootmedia]
# 
#     If test is provided, exitcode will be 0 or 1
# 
# Examples:
#     $ livestate
#     bootmedia:  cdr
#     rootfs: ram
# 
#     $ livestate rootfs
#     ram
# 
#     $ livestate rootfs=ram; echo $?
#     0

LIVEMOUNT="/media/live"

fatal() {
    echo error: $@ 1>&2
    exit 1
}

usage() {
    echo "Syntax: $0 [test[=result]]"
    sed -n '1d; s/^# //p' $0
    exit 2
}

get_bootmedia() {
    if [ -e "$LIVEMOUNT/isolinux/isolinux.cfg" ]; then
        echo cdr
    elif [ -e "$LIVEMOUNT/syslinux.cfg" ]; then
        echo usb
    else
        fatal "could not determine bootmedia"
    fi
}

get_rootfs() {
    if grep -q "/dev/shm $LIVEMOUNT tmpfs rw" /proc/mounts; then
        echo ram
    else
        echo bootmedia
    fi
}

check_state() {
    state=$1

    check=${state%=*}

    if [ "$check" = "bootmedia" ]; then
        value=$(get_bootmedia)
    elif [ "$check" = "rootfs" ]; then
        value=$(get_rootfs)
    else
        fatal "state check not found: $check"
    fi

    # only one argument
    if [ "$check" = "$state" ]; then
        echo $value
        return 0
    else
        result=${state#*=}
        if [ "$result" = "$value" ]; then
            return 0
        else
            return 1
        fi
    fi
}

[ -e $LIVEMOUNT ] || fatal "livemount does not exist: $LIVEMOUNT"

[ "$1" = "-h" ] && usage

if [ $# = 0 ]; then
    echo bootmedia: $(get_bootmedia)
    echo rootfs: $(get_rootfs)
elif [ $# = 1 ]; then
    if check_state $1; then
        exit 0
    else
        exit 1
    fi
else
    usage
fi
