#!/bin/sh

#******Functions********
function showUsage ()
{
    echo $"Usage: $0 [options] device"
    echo $"               [-t <device type(must be disk to work)>]"
    echo $"               [-h|--help]"
}

# Read the 4-byte signature written to the disk at an offset of 440 bytes 
function getDeviceSig()
{
    dev_sig=`od -t x4 -A n --skip-bytes=440 --read-bytes=4 $node | awk '{print $1}'`
}

# The disk signature reported by EDD can be found in the 
# /sys/firmware/edd/int13_dev8* directories
# For the signature found on the device node passed to this program,
# we have to scan all of the int13_dev8* mbr_signature files to verify
# which disk is which int13_dev device. If the disk signature matches
# more than one mbr_signature, we don't know which int13_dev is correct,
# so we just exit. The signature for each disk needs to be unique for 
# this to work correctly. 

function getMBRSig()
{
    for i in `ls /sys/firmware/edd` 
    do
        mbr_sig=`cat /sys/firmware/edd/$i/mbr_signature | cut -dx -f2`
        if [ "$mbr_sig" == "$dev_sig" ]; then
            if [ "$match" == '' ]; then
                match=$i
            else
                match=""
                break
            fi
        fi
    done    
    
}

# Get the device signature, then do the comparisons to figure out which
# int13_dev is correct. Then export that info to udev
function getEDDName()
{
    getDeviceSig
    getMBRSig
    if ! [ "$match" == "" ]; then
        echo "ID_BIOSDISK=$match"
    fi
}

#******Variables*********
match=""
node=""

#******Main**************
if [ $# -eq 0 ]; then
    showUsage
    exit 1
fi

while [ $# -gt 0 ]; do
    if [ "$1" -a "$2" ]; then
        case $1 in
            -t*)
                id_type=$2
                shift
                ;;
            *)
                showUsage
                exit 1
                ;;
        esac
    elif [ "$1" -a -z"$2" ]; then
        case $1 in
            -h|--help)
                showUsage
                exit 1
                ;;
            *)
                node=$1
                ;;
        esac
    fi
    shift
done

#if the edd module isn't loaded, this won't work, so exit
if [ `lsmod | grep -c "edd"` -lt 1 ]; then
    exit 0
fi

#if the device is not a disk, then this is of no use, so exit
if ! [ "$id_type" == "disk" ]; then
    exit 0
fi

#run it
getEDDName
