# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
#----------------------------------------------------------------------
# Modifications Copyright (c) 2022 Advanced Micro Devices, Inc. All rights reserved.
# Notified per clause 4(b) of the license.
#
#----------------------------------------------------------------------


#!/bin/sh

BASEDIR=$(dirname "$0")
FUNCTION_FILTER=$1
FILTER=$2
FILTER_BY_FILENAME=$3

# Check Python version
REQUIRED_PYTHON_VERSION="3.8"
PYTHON_VERSION=$(python3 --version 2>&1 | awk '{print $2}')

# Compare version
if [ "$(printf '%s\n' "$REQUIRED_PYTHON_VERSION" "$PYTHON_VERSION" | sort -V | head -n1)" != "$REQUIRED_PYTHON_VERSION" ]; then
        echo "Error: Python version 3.8 or greater is required. You are using Python $PYTHON_VERSION."
fi

python3 $BASEDIR/SearchMmergeYAMLFiles.py

if [ -f optimization_database.yaml ]; then
 echo "Generating the Optimizer Report Output..."
 python3 $BASEDIR/opt-viewer.py --generate_report_of_type=text optimization_database.yaml $FUNCTION_FILTER $FILTER $FILTER_BY_FILENAME
 mv $PWD/reports/Optimization_Report.txt optimization_report.aor
 find $PWD -type f -name "*.opt.yaml" -exec rm -f {} \;
 rm -rf optimization_database.yaml
 rm -rf $PWD/reports
 echo "AMD Optimization Report (AOR) generated."
fi

if [ -f optimization_database.ld.yaml ]; then
 echo "Generating the ld Optimizer Report Output..."
 python3 $BASEDIR/opt-viewer.py --generate_report_of_type=text optimization_database.ld.yaml $FUNCTION_FILTER $FILTER $FILTER_BY_FILENAME
 mv $PWD/reports/Optimization_Report.txt optimization_ld_report.aor
 find $PWD -type f -name "*.opt.ld.yaml" -exec rm -f {} \;
 rm -rf optimization_database.ld.yaml
 rm -rf $PWD/reports
 echo "Link time AMD Optimization Report (AOR) generated."
fi

if [ -f aor_screen_list ]; then 
    if [ -f optimization_report.aor ]; then
     echo "AMD Compile Time Optimization Report Messages Listing : Begin..."
     cat optimization_report.aor
     echo "AMD Compile Time Optimization Report Messages Listing : End."
    fi

    if [ -f optimization_ld_report.aor ]; then
     echo "AMD Link Time Optimization Report Messages Listing : Begin..."
     cat optimization_ld_report.aor
     echo "AMD Link Time Optimization Report Messages Listing : End."
    fi
    rm aor_screen_list
fi
