#!/bin/sh
# -*- coding: utf-8; indent-tabs-mode: nil; tab-width: 4; c-basic-offset: 4; -*-
# vim:fileencodings=utf-8:expandtab:tabstop=4:shiftwidth=4:softtabstop=4

check_vga()
{
    lspci -n | grep --quiet --extended-regexp "^[0-9a-f:.]* 03[80][02]: $1"
}

trigger_reboot()
{
    local stage=${1:-task}
    touch /usr/share/volatile/${stage}-reboot
}

check_reboot()
{
    local stage=${1:-task}
    test -f /usr/share/volatile/${stage}-reboot
}

clean_reboot_trigger()
{
    local stage=${1:-task}
    local trigger=/usr/share/volatile/${stage}-reboot
    rm -f $trigger
}

check_pciid()
{
    local pciid="$*"
    local result=0

    for id in $pciid; do
    	if lspci -n -d $id | grep $id > /dev/null 2>&1; then
	        result=1
	    fi
    done

    if [ $result = 1 ]; then
    	true
    else
	    false
    fi
}

check_usbid()
{
    local usbid="$*"
    local result=0

    for id in $usbid; do
    	if lsusb -d $id | grep $id > /dev/null 2>&1; then
	        result=1
	    fi
    done

    if [ $result = 1 ]; then
    	true
    else
	    false
    fi
}

check_device()
{
    local device="$*"

    if check_pciid $device; then
    	true
    elif check_usbid $device; then
	    true
    else
	    false
    fi
}

# check codec with vendor name
#
# Arguments:
#     $1 : vendor name
# Return:
#     $? : True or False
check_codec()
{
    cat /proc/asound/card*/codec\#* | grep -iq "^Codec: $1"
}

# check if this codec installed
# 
# Arguments: 
#     $1 : "vendor_id:chip_id"
# Return:
#     $? : True or False
check_hdacodec()
{
    result=0   
    target_vendor_id=$(echo $1 | sed -e 's/^/0x/g' -e 's/://g')

    for CODEC_DIR in /sys/class/sound/hw*; do
        vendor_name=`cat $CODEC_DIR/vendor_name`
        chip_name=`cat $CODEC_DIR/chip_name`
        echo "vendor: $vendor_name, chip: $chip_name"
        vendor_id=`cat $CODEC_DIR/vendor_id`

        if [ "$vendor_id" = "$target_vendor_id" ]; then
            result=1
        fi
  
    done

    if [ $result = 1 ]; then
        true
    else
        false
    fi
}

# To get codec card address
# 
# Arguments: 
#     $1  :  vendor id of codec
# Return:
#     RET : returned value which is address number of codec
get_codec_address()
{
    target_vendor_id=$1
    for CODEC_DIR in /sys/class/sound/hw*;
    do
        vendor_id=`cat $CODEC_DIR/vendor_id`
        if [ "$vendor_id" = "$target_vendor_id" ]; then
            addr=`basename $CODEC_DIR`
            addr=`echo $addr | cut -c 4`
            break
        fi
    done  
    RET=$addr
}
