#!/bin/sh
#
#   parse_nextpnr_stats.sh - Reads a nextpnr json report file and generates some basic statistics about the design
#
#   Copyright (c) 2024 Efthymios Kritikos
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
set -eu

if ! which jq &> /dev/null
then
	echo to get statistics, please install jq
	exit 0
fi

REPORT_TYPE=brief

if [ $# == 0 ]
then
	echo $0' [report type] <report json file>'
	exit 1
elif [ $# == 2 ]
then
	case "$1" in
		"--brief")
			REPORT_TYPE=brief
			;;
		*)
			echo unknown parameter "\"$1\""
			exit 1
			;;
	esac
	REPORT=$2
else
	REPORT=$1
fi

if ! [ -e "$REPORT" ]
then
	echo file "\"${REPORT}\"" doesn\'t exist!
	exit 1
fi

LUT_AVAIL=$(jq '.utilization.TRELLIS_COMB.available' "$REPORT" )
LUT_USED=$(jq '.utilization.TRELLIS_COMB.used' "$REPORT" )
FF_AVAIL=$(jq '.utilization.TRELLIS_FF.available' "$REPORT" )
FF_USED=$(jq '.utilization.TRELLIS_FF.used' "$REPORT" )
FREQ_GOT=$(jq '.fmax."$glbnet$CPU_SPEED".achieved' "$REPORT" |grep -o '..\..')
FREQ_MAX=$(jq '.fmax."$glbnet$CPU_SPEED".constraint' "$REPORT" |grep -o '..\..')

if [ "$REPORT_TYPE" == "brief" ]
then
	printf '\e[1;30m'
	echo Luts $LUT_USED/$LUT_AVAIL \($(echo "($LUT_USED*100)/$LUT_AVAIL"|bc -l|grep -o '^.*\..')%\)
	echo Flip Flops $FF_USED/$FF_AVAIL \($(echo "($FF_USED*100)/$FF_AVAIL"|bc -l|grep -o '^.*\..')%\)
	echo Max CPU freq $FREQ_GOT/$FREQ_MAX
	printf '\e[0m'
fi
