#!/bin/bash
# init.sh                                              2022-04-29 Agner Fog
# Modified by Hosein Yavarzadeh
# Initialization of files before running test scripts
# (c) Copyright 2014-2022 by Agner Fog. GNU General Public License www.gnu.org/licenses


# make all scripts executable
chmod u+x *.sh*

# Compile cpugetinfo.cpp if modified
if [ cpugetinfo.cpp -nt cpugetinfo ] ; then
   echo "Compiling cpugetinfo.cpp"
   g++ -O2 -m64 -fno-pie -no-pie -ocpugetinfo cpugetinfo.cpp
fi

# Create cpuinfo.txt with instruction sets
# if [ cpugetinfo -nt cpuinfo.txt ] ; then
echo "Creating file cpuinfo.txt"
./cpugetinfo instructionsets > cpuinfo.txt
# fi

# Check if 32 bit mode included
if [ -n "$1" -a 1$1 -eq 164 ] ; then
   echo "64 bit only"
   echo " no32bit " >> cpuinfo.txt
   use32=0
else
   echo "32 and 64 bits"
   use32=1
fi

# Detect CPU specific variables, etc.
. vars.sh

# Check if nasm version is high enough
nasmversion=`nasm -v | sed 's/[^0-9]*\([0-9.]*\).*/\1/' | sed 's/\.//g'`
if [ `./cpugetinfo -avx2` -gt 0 -a $nasmversion -lt 21000 ] ; then
  echo 'Warning: nasm version too low for AVX2 instruction set'
elif [ `./cpugetinfo -avx` -gt 0 -a $nasmversion -lt 20400 ] ; then
  echo 'Warning: nasm version too low for AVX instruction set'
fi
# Make countertypes.inc file with CPU specific variables etc.
# This file will be included in script templates
echo "Creating file countertypes.inc"
echo -e "; This file is autogenerated. Edit vars.sh and init.sh instead"  > countertypes.inc
echo -e "\n; Operating system:"  >> countertypes.inc
echo -e "%define `./cpugetinfo system` 1"  >> countertypes.inc
echo -e "\n; CPU:"  >> countertypes.inc
echo -e "%define CPUbrand `./cpugetinfo vendor`"  >> countertypes.inc
echo -e "%define ifamily `./cpugetinfo family`"  >> countertypes.inc
echo -e "%define imodel `./cpugetinfo model`"  >> countertypes.inc
echo -e "\n; Define whether AVX and YMM registers used"  >> countertypes.inc
if   [ `grep -c -i "avx" cpuinfo.txt ` -ne 0 ] ; then
echo -e "%define  USEAVX   1"  >> countertypes.inc
else
echo -e "%define  USEAVX   0"  >> countertypes.inc
fi
echo -e "\n; PMC counters:"  >> countertypes.inc
echo -e "%ifndef counters"  >> countertypes.inc
echo -e "%define counters $PMCs"  >> countertypes.inc
echo -e "%endif\n"  >> countertypes.inc