#!/usr/bin/bash
# Copyright (C) 2014 McAfee, Inc. All rights reserved.
# script to parse SDR and strip out any software sensor records
# (since the BMC doesn't handle these, the OS does)
# p1=output file - new binary SDR
# p2=optional cached SDR

td=$(mktemp -t -d ipmi_sdr_fix.XXXXXX)
exec >$td/stdout 2>$td/stderr

tidy_up () {
    [[ $? -eq 0 && -z $debug ]] && rm -rf $td
}

trap tidy_up EXIT

if [[ -z $1 ]] ; then
    echo "Arg 1 must be output SDR filename" >&2
    exit 1
fi

if [[ -n $2 ]] ; then
    if [[ -s $2 ]] ; then
        t=$2
    else
        echo "Arg 2 must be SDR cache file" >&2
        exit 1
    fi
else
    t2=$td/sdrdump
    t=$t2
    # must run the explicit binary not the wrapper!
    ipmitool sdr dump $t
fi

a='
BEGIN{
    # the start offset of the record
    rec_start=-1
    # the total length of the record
    rec_len=0
    # the number of bytes in this record we have yet to parse
    rec_missing=0
    # the byte counter within the record of bytes we already have
    rec_offset=0
    # number of input bytes expected on one line
    inlinebytes=16
    # which part of a record we are processing
    state=0 # 1=in header 2=in body
    # count of bytes dropped
    dropped=0
}

# print an individual record
function print_rec() {
    if (rec_start > -1) {
        # if we have a record
        # warn if parsing might have failed
        if (rec_hex[2] != "51") { printf "Record starting at 0x%x does not have 51 in the correct place!",rec_start >"/dev/stderr" }

        # look for record types 1 and 2 (the only ones with the owner ID requiring fixups)
        # and an owner ID which has its LSB set
        if ((strtonum("0x" rec_hex[3]) < 3) && (strtonum("0x" rec_hex[5]) % 2)) {
            printf "Record %s %s type %s owner %s starting at 0x%x is software only and being dropped\n",rec_hex[0],rec_hex[1],rec_hex[3],rec_hex[5],rec_start >"/dev/stderr"
            if (debug > 0) {
                printf "Dropped record:\n  " >"/dev/stderr"
                for(i=0; i<rec_len; i++) {
                    printf "%s ",rec_hex[i] >"/dev/stderr"
                }
                printf "\n  " >"/dev/stderr"
                for(i=0; i<rec_len; i++) {
                    printf "%s",rec_string[i] >"/dev/stderr"
                }
                printf "\n" >"/dev/stderr"
            }
            dropped+=rec_len
        } else {
            # otherwise print the record
            print_rec_real()
        }
    } else {
        if (debug > 1) { printf "rec_start is -1\n" >"/dev/stderr" }
    }

    # prepare for next record
    rec_start=-1
    delete rec_hex
    delete rec_string
    rec_len=0
    rec_offset=0
    hdr_loc=0
    state=0
}

# print the hex byte values of this record
# no line breaks or anything since xxd gets confused
function print_rec_real() {

    if (debug > 0) {
        printf "Keep record: " >"/dev/stderr"
        for(i=0; i<rec_len; i++) {
            printf "%s ",rec_hex[i] >"/dev/stderr"
        }
        printf "\n" >"/dev/stderr"
    }

    i=0
    while (i < rec_len) {
        printf "%c",strtonum("0x"rec_hex[i])
        ++i
    }
}

# consume bytes from the input line into the record body
function parse_body () {
    while ((lineused < thislinebytes) && (rec_missing > 0)) {
        if (debug > 1) {
            printf "%d:%d:B:%d:%d:%d\n",FNR,state,lineused,rec_missing,rec_offset >"/dev/stderr"
        }
        rec_hex[rec_offset]=$(2+lineused)
        rec_string[rec_offset]=substr($0,59+lineused,1)
        lineused++
        rec_missing--
        rec_offset++
    }

    # if the record is now complete then print it
    if (rec_missing == 0) {
        print_rec()
    }
}

# record the bytes consumed in this line so far
# record the number of bytes on this line
{
    lineused=0
    thislinebytes=NF-1
}

(debug>1) {
    printf "%d:%d:%d:%s\n",FNR,state,thislinebytes,$0 >"/dev/stderr"
}

{
    # keep alternating between body and header reads until the line is consumed
    while (lineused < thislinebytes) {
        # if we are in a record already then append the required bytes
        if (state == 2) { parse_body() }

        # if we are not in a record then parse the header bytes
        if (state != 2) {
            if (state == 0) {
                rec_start=strtonum("0x"$1)+lineused
                state=1
            }
            while ((lineused < thislinebytes) && (hdr_loc < 5)) {
                if (debug > 1) {
                    printf "%d:%d:H:%d:%d:%d:%d:%s\n",FNR,state,lineused,rec_missing,rec_offset,hdr_loc,$(2+lineused) >"/dev/stderr"
                }
                rec_hex[rec_offset]=$(2+lineused)
                rec_string[rec_offset]=substr($0,59+lineused,1)
                lineused++
                rec_offset++
                hdr_loc++
            }

            if (hdr_loc == 5) {
                # now have complete header, initiate body parse
                state = 2
                rec_missing = strtonum("0x" rec_hex[4])
                rec_len = 5 + rec_missing
                if (debug > 1) { printf "%d:%d:H:%d:%d:%s\n",FNR,state,rec_missing,rec_len,rec_hex[4] >"/dev/stderr" }
            }
        }
    }
}
END {
    printf "Dropped %d bytes\n",dropped >"/dev/stderr"
}
'

# convert the input SDR to a hex dump
LANG=C od -t x1 $t >$td/in.hex
# filter it
awk -v debug=$debug "$a" $td/in.hex >$td/out.bin
# and put it into place
chmod 644 $td/out.bin
mv $td/out.bin $1

