#!/bin/bash

me=`basename $0`
VendorID=$2
ProductID=$3
FriendlyName=$4

Plist="$ccid_plist" && [ ! -n "$Plist" ] && Plist=$1;
Awk=`which awk` && [ ! -n "$Awk" ] &&  Awk=`which gawk`;

function log
{
    sev=$1
    msg=$2
    
    logger -p $sev -t $me $msg;
    echo "$me [$sev] $msg";
}

function log_err
{
    log user.error "$1" >&2;
}

function log_wrn
{
    log user.warning "$1" >&2;
}

function usage
{
    log_err "Invalid command line arguments or ccid_plist env variable not set";
    echo "$me <path to PS/SC ccid driver's Info.plist>";
}

[ ! -n "$Plist" ] && usage && exit 1;
[ ! -n "$Awk" ]   && log_err "awk(gawk) not found" && exit 2;

function check_ccid_settings
{
    plist=$1
    
    x=`cat $plist | $Awk "
	BEGIN {
	    no_need_to_insert[0]=\"ifdVendorID\";
	    no_need_to_insert[1]=\"ifdProductID\";
	    no_need_to_insert[2]=\"ifdFriendlyName\";
	}
	/$VendorID/ {no_need_to_insert[0]=\"\"}
	/$ProductID/ {no_need_to_insert[1]=\"\"}
	/$FriendlyName/ {no_need_to_insert[2]=\"\"}
	END {print no_need_to_insert[0] \" \" no_need_to_insert[1]\" \" no_need_to_insert[2]}
	"`
	
	[ $? != 0 ] && log_err "Find section to update failed $?" && exit $?;

	[[ "$x" == *ifd* ]] && echo "ifdVendorID ifdProductID ifdFriendlyName" && exit 0;

	[ "$x" == "   " ] && log_wrn "No need to update any section" || log_wrn "Sections to update $x";
	
	echo $x;
}    

function update_ccid_settings
{    
    need_to_insert=$2;
    plist=$1;
    awk_code="";
    for i in $need_to_insert; do
	case "$i" in
	'ifdVendorID')
	awk_code="$awk_code""/ifdVendorID/ {
	    skip=1;
	    print \"<array>\";
	    print \"<string>$VendorID</string>\";
	    next;
	    }"
	    ;;
	'ifdProductID')
	    awk_code=$awk_code"/ifdProductID/ {
	    skip=1;
	    print \"<array>\";
	    print \"<string>$ProductID</string>\";
	    next;
	    }"
	;;
	'ifdFriendlyName')
	awk_code="$awk_code""/ifdFriendlyName/ {
	    skip=1;
	    print \"<array>\"
	    print \"<string>$FriendlyName</string>\";
	    next;
	    }"
	;;
	esac
    done
    cat $plist | $Awk "BEGIN {skip=0} skip == 1 { skip=0; next }
	{print \$0}
	$awk_code"
	
    r=$?
    [ $r != 0 ] && log_err "Update sections to update $r" && exit $r;

    return $r;
}

# log_wrn "vid:$VendorID pid:$ProductID fn:$FriendlyName";
need_to_insert=$(check_ccid_settings $Plist)
update_ccid_settings $Plist "${need_to_insert}";
r=$?;
[ $r == 0 ] || log_err "$Plist processing failed";

exit $r;
