#!/bin/sh

# usage:
#     nvram_get [dev] <key>
#     nvram_set [dev] <key> <value>


usage()
{
    echo "Usage:"
    echo "    nvram_get [dev] <key>"
    echo "    nvram_set [dev] <key> <value>"
    echo ""
    echo "This a wrapper script which provides compatible tools as LSDK \"nvram_set\" and \"nvram_get\"."
    echo "It uses \"wificonf\" as a underlying tool, check \"wificonf -h\" for more usage."
}

if [ "$0" == "nvram_set" -o "$0" == "/usr/bin/nvram_set" ]; then
    CMD=set
    if [ 2 == $# ]; then
        KEY=$1
        VAL=$2
    elif [ 3 == $# ]; then
        DEV=$1
        KEY=$2
        VAL=$3
    else
        usage
        exit 1
    fi
else
    CMD=get
    if [ 1 == $# ]; then
        KEY=$1
    elif [ 2 == $# ]; then
        DEV=$1
        KEY=$2
    else
        usage
        exit 1
    fi
fi

# first, check if there're soft-links for wifi profiles
if [ "$DEV" != "" ]; then
    PROFILE=`readlink /tmp/mtk/wifi/$DEV`
else
    PROFILE=`readlink /tmp/mtk/wifi/2860`
fi

# else, try default mapping with l1profile:
#     2880  -> 1st card
#     rtdev -> 2nd card
#     wifi3 -> 3rd card

if [ "$PROFILE" == "" ]; then
    if [ -f /etc/wireless/l1profile.dat ]; then
        # first line "Default" is illegal in shell
        cat /etc/wireless/l1profile.dat | tail -n +2 > /tmp/l1profile.sh;
        . /tmp/l1profile.sh;
        case "$DEV" in
        2860)
            PROFILE=$INDEX0_profile_path
            ;;
        rtdev)
            PROFILE=$INDEX1_profile_path
            ;;
        wifi3)
            PROFILE=$INDEX2_profile_path
            ;;
        *)
            PROFILE=$INDEX0_profile_path
            ;;
        esac
    fi
fi

# Fatal error: still cannot find correct $PROFILE !
if [ "$PROFILE" == "" ]; then
    echo "Error: nvram_$CMD is not configured properly!" >&2
    echo "Either you don't have a valid \"/etc/wireless/l1profile.dat\" , or you forgot to do something like:" >&2
    echo "    mkdir -p /tmp/mtk/wifi" >&2
    echo "    ln -s /etc/wireless/mt76xx/mt76xx.dat /tmp/mtk/wifi/xxxx" >&2
    exit 1
fi

############ Final Wrapper ############

if [ -f /usr/bin/wificonf ]; then
    /usr/bin/wificonf -f $PROFILE $CMD $KEY $VAL
else
    echo "Error: unabled to locate wificonf!" >&2
    exit 1
fi

