#!/bin/sh
# PCP QA Test No. 1733
# window-size dstat test using stty
# - split off from qa/1187
#
# Copyright (c) 2018-2021 Red Hat.  All Rights Reserved.
#

seq=`basename $0`
echo "QA output created by $seq"

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

which pcp-dstat >/dev/null 2>&1 || _notrun "pcp-dstat not installed"
[ -t 1 ] || _notrun "stdout is not a tty, stty will hang"

_cleanup()
{
    cd $here
    if which stty >/dev/null 2>&1
    then
	[ -n "$SAVE_COLUMNS" ] && stty cols $SAVED_COLUMNS >/dev/null 2>&1
	SAVE_COLUMNS=''
	[ -n "$SAVE_LINES" ] && stty rows $SAVED_LINES >/dev/null 2>&1
	SAVE_LINES=''
    fi
    $sudo rm -rf $tmp $tmp.*
}

status=0	# success is the default!
username=`id -u -n`
trap "_cleanup; exit \$status" 0 1 2 3 15

# read from the pcp-dstat archive with various dstat options
#
dstat_archive()
{
    archive="$1"
    message="$2"
    shift
    shift
    options="$@"

    echo "$message" >>$seq_full

    pcp_options="pcp -z --origin=+0.1 --archive $archive"
    $pcp_options dstat --time $options 1 3 >$tmp.out 2>$tmp.err

    echo "=== std out" >>$seq_full
    cat $tmp.out >>$seq_full
    echo "=== std err" >>$seq_full
    cat $tmp.err >>$seq_full
}

dstat()
{
    dstat_archive "$here/archives/pcp-dstat" "$@"
}

filter_info()
{
    sed \
	-e "/^$(printf '\t')/d" \
	-e "/^.GCC /d" \
	-e "s/^Python .*/Python VERSION/g" \
	-e "s,$PCP_SYSCONF_DIR,/etc/pcp,g" \
	-e "s,pcp-dstat $PCP_VERSION,pcp-dstat VERSION,g" \
	-e "s/\"User:\",\"$username\"/\"User:\",\"USER\"/g" \
	-e "s/\"Date:\",\".*\"/\"Date:\",\"DATE\"/g" \
	-e "s,-o $tmp.csv,-o TMP.csv,g" \
    #end
}

SAVE_COLUMNS=''
SAVE_LINES=''

# real QA test starts here

# verify no terminal size effects on CSV output
dstat "CSV terminal default" -tfvnrl -o $tmp.csv
mv $tmp.csv $tmp.csvterm0
cat $tmp.csvterm0 >>$seq_full
# window geometry to be restored, possibly from environment
#
SAVED_COLUMNS=$COLUMNS
SAVED_LINES=$LINES
if which tput >/dev/null 2>&1
then
    # more likely to be correct
    #
    SAVED_COLUMNS=`tput cols`
    SAVED_LINES=`tput lines`
fi
# sane defaults if all else fails
#
[ -z "$SAVED_COLUMNS" ] && SAVED_COLUMNS=80
[ -z "$SAVED_LINES" ] && SAVED_LINES=24
echo "initial window: $SAVED_COLUMNS columns and $SAVED_LINES lines" >>$seq_full
# try to reduce terminal size
#
if which stty >/dev/null 2>&1
then
    stty cols 40 >/dev/null 2>&1
    stty rows 40 >/dev/null 2>&1
fi
# and output should be unchanged
#
dstat "CSV terminal reduced" -tfvnrl -o $tmp.csv
mv $tmp.csv $tmp.csvterm1
echo >>$seq_full
cat $tmp.csvterm1 >>$seq_full
echo "Silence is golden ..."
diff $tmp.csvterm0 $tmp.csvterm1

# success, all done
exit
