#! /bin/sh

# Copyright (c) 2012, Wind River Systems, Inc.
#
# The right to copy, distribute, modify, or otherwise make use
# of this software may be licensed only pursuant to the terms
# of an applicable Wind River license agreement.
set -u
[ -f /etc/tcgbox_funcs.sh ] && source /etc/tcgbox_funcs.sh || exit 1

function usage
{
    echo "$0"
    echo ""
}

function handle_owned_cat
{
    case $(cat $1) in
        "0")
            printf "%-20s%-10s\n" "Owned Status:" "Not Owned"
            printf "%-20s%-10s\n" "Cleared Status:" "Cleared"
            ;;
        "1")
            printf "%-20s%-10s\n" "Owned Status:" "Owned"
            printf "%-20s%-10s\n" "Cleared Status:" "Not Cleared"
            ;;
    esac
}

function handle_active_cat
{
    case $(cat $1) in
        "0")
            printf "%-20s%-10s\n" "Active Status:" "Not Actived"
            ;;
        "1")
            printf "%-20s%-10s\n" "Active Status:" "Actived"
            ;;
    esac
}

function handle_enabled_cat
{
    case $(cat $1) in
        "0")
            printf "%-20s%-10s\n" "Enabled Status:" "Disabled"
            ;;
        "1")
            printf "%-20s%-10s\n" "Enabled Status:" "Enabled"
            ;;
    esac
}

function handle_caps_cat
{
    echo ""
    cat $1|awk -v FS=':' '{
        printf ("%-19s%-10s\n", $1 ":", $2);
    }'
    echo ""
}

function handle_misc_tpm0_uevent_cat
{
    cat $1|awk -v FS='=' '
        /MAJOR/ {
            printf ("%-20s%-10s\n", "Major Dev No:", $2);
        }

        /MINOR/ {
            printf ("%-20s%-10s\n", "Minor Dev No:", $2);
        }

        /DEVNAME/ {
            printf ("%-20s%-10s\n", "Device Node Name:", "/dev/" $2);
        }
    '
}

# Initial Section
QUIET=0
DEP_LIST="awk cat tpm_sanitycheck"
SYSFS_CAT_LIST="owned active enabled caps misc/tpm0/uevent"

# Print Banner
echo "TPM Statistic - Version 1.0"
echo ""

# Check Environment
for i in ${DEP_LIST}; do
    if ! env_check $i; then
        echo ""
        echo "Invalid Environment! Exit!"
        exit 1
    fi  
done
echo ""

# Call Statistic Functions
if ! ${TPM_SANITYCHECK} -dsq; then
    echo "[ TPM Basic Environment Not Available ]"
    echo ""
    exit 1
fi 
printf "%-20s%-10s\n" "TPM Chip Presence:" "Normal"

cd /sys/class/misc/tpm0/device
for i in ${SYSFS_CAT_LIST}; do
    FUNC=handle_${i//\//_}_cat
    eval ${FUNC} ${i}
done
echo ""

cd ${OLDPWD}
exit 0
