#! /bin/sh
# PCP QA Test No. 653
# checks __pmSetProcessIdentity function in libpcp
#
# Copyright (c) 2012 Red Hat, Inc.  All Rights Reserved.
#
seq=`basename $0`
echo "QA output created by $seq"

# get standard environment, filters and checks
. ./common.product
. ./common.filter
. ./common.check

[ $PCP_VER -ge 30611 ] || _notrun "Needs a more recent libpcp version"

_cleanup()
{
    $sudo rm -f $tmp.*
    exit $status
}

_filter_err()
{
    pid=$1

    # [Fri Nov 23 11:04:47] username(6802)
    sed \
	-e 's/\[.* [0-9 ][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]\]/[TIMESTAMP]/g' \
	-e "s/$pid/PID/g"
}

_filter_out()
{
    uid=$1

    sed \
	-e "s,$here/src,src,g" \
	-e "s/$uid/as local user/g"
}

_filter_ps()
{
    pid=$1
    uid=$2

    tee -a $seq.full | \
    $PCP_AWK_PROG '
NR == 1	{ if ($2 != "PID") {
	    print "PID not in field 2 of ps output!"
	    exit(1)
	  }
	  if ($1 != "UID") {
	    print "UID not in field 1 of ps output!"
	    exit(1)
	  }
	  if ($8 == "CMD")
	    # Linux
	    cmd = 8
	  else if ($11 == "COMMAND")
	    # Darwin
	    cmd = 11
	  else {
	    print "CMD (or COMMAND) not in field 8 (or 11) of ps output!"
	    print
	    exit(1)
	  }
	  next
	}
$1 == "'$uid'" && $2 == '$pid' {
	  print "found:",$cmd,$(cmd+1),$(cmd+2),$(cmd+3),$(cmd+4)
	  exit(0)
	}
END	{ exit(1) }'
}

status=1	# failure is the default!
username=`id -u -n`	# me, myself & I
trap "_cleanup" 0 1 2 3 15
$sudo rm -f $tmp.* $seq.full

# real QA test starts here
echo "== failing case, should error out" | tee -a $seq.full
$here/src/username nosuchuser >$tmp.err 2>&1 &
pid=$!
sleep 1	# give it a chance to start
ps $PCP_PS_ALL_FLAGS | _filter_ps $pid nosuchuser
$sudo $PCP_BINADM_DIR/pmsignal -a username
wait $pid
[ -s $tmp.err ] && cat $tmp.err | _filter_err $pid

echo "== passing case, should be local user" | tee -a $seq.full
$here/src/username $username &
pid=$!
sleep 1	# give it a chance to start
ps $PCP_PS_ALL_FLAGS | _filter_ps $pid $username >$tmp.out
$sudo $PCP_BINADM_DIR/pmsignal -a username
wait $pid
[ -s $tmp.out ] && cat $tmp.out | _filter_out $username

status=0
exit
