#!/bin/bash

#
# Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may
# not use this file except in compliance with the License. A copy of the
# License is located at
#
#     http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
#

if [ -z "$SDK_DIR" ]; then
	echo "Error: SDK_DIR environment variable is not set.  Please 'source sdk_setup.sh' from the aws-fpga directory first."
	exit 1
fi

if [ $EUID != 0 ]; then
	echo ""
	echo "Root privileges are required to install. You may be asked for your password..."
	sudo -E "$0" "$@"
	exit $?
else
	echo "Executing as root..."
	echo ""
fi

BASE_PATH=/usr/local

# check to see if the /usr/local/bin is on the sudo PATH (is secure_path enabled?)
echo $PATH | grep "$BASE_PATH"
ret=$?
if [ $ret -ne "0" ]; then
	BASE_PATH=/usr
fi

SDK_MGMT_DIR=$SDK_DIR/userspace
AFI_MGMT_TOOLS_SRC_DIR=$SDK_MGMT_DIR/fpga_mgmt_tools/src
AFI_MGMT_TOOLS_DST_DIR=$BASE_PATH/bin
AFI_MGMT_TOOLS_LIB_DIR=$SDK_MGMT_DIR/lib/so

# in order to accommodate different distributions, check several options for the user-libraries directory
if [ -d "/usr/local/lib64" ]; then
	AFI_MGMT_LIBS_DST_DIR=/usr/local/lib64
elif [ -d "/usr/local/lib" ]; then
	AFI_MGMT_LIBS_DST_DIR=/usr/local/lib
elif [ -d "/usr/lib64" ]; then
	AFI_MGMT_LIBS_DST_DIR=/usr/lib64
elif [ -d "/usr/lib" ]; then
	AFI_MGMT_LIBS_DST_DIR=/usr/lib
else
	echo "Error: No directory for installing libraries."
	exit 1
fi

if [ ! -d "$AFI_MGMT_TOOLS_DST_DIR" ]; then
	mkdir -p $AFI_MGMT_TOOLS_DST_DIR
fi

# /usr/bin requires sudo permissions
echo "AWS FPGA: Copying Amazon FPGA Image (AFI) Management Tools to $AFI_MGMT_TOOLS_DST_DIR"
cp -f $AFI_MGMT_TOOLS_SRC_DIR/fpga-* $AFI_MGMT_TOOLS_DST_DIR
cp -f $AFI_MGMT_TOOLS_LIB_DIR/libfpga_mgmt.so.1.0.0 $AFI_MGMT_LIBS_DST_DIR
ln -sf libfpga_mgmt.so.1 $AFI_MGMT_LIBS_DST_DIR/libfpga_mgmt.so
ln -sf libfpga_mgmt.so.1.0.0 $AFI_MGMT_LIBS_DST_DIR/libfpga_mgmt.so.1

source /tmp/sdk_root_env.exp
if allow_non_root ; then
  chmod u+s $AFI_MGMT_TOOLS_DST_DIR/fpga-local-cmd
fi

echo "AWS FPGA: Installing shared library to $AFI_MGMT_LIBS_DST_DIR"
ld_conf_change="0"
while true; do
	# update the dynamic linker cache
	ldconfig

	# confirm that the linker cache stored the library we want
	ldconfig -p | grep "libfpga_mgmt\.so\.1"
	ret=$?
	if [ $ret -ne "0" ]; then
		if [ "$ld_conf_change" -eq "1" ]; then
			echo "Error: Unable to automatically install the fpga_mgmt library."
			exit 1
		fi
		ld_conf_change="1"
		echo "$AFI_MGMT_LIBS_DST_DIR" > /etc/ld.so.conf.d/fpga_mgmt-x86_64.conf
	else
		break
	fi
done
echo "AWS FPGA: Installing python bindings for FPGA management library"
cat>/tmp/mod_search_path<<EF
rm -f /tmp/py_install_paths
if [[ \$? -ne 0 ]] ; then
	echo "Could not install python modules"
	exit 1
fi
for i in 2 3 ; do
	which python\$i >/dev/null 2>&1 || continue
	python\$i -c "import sys
print(sys.path)
" | tr , '\n' | tr -d "'[]" | grep -E "64.*site-packages$" >> /tmp/py_install_paths
done
EF
bash /tmp/mod_search_path
while read -t 2 site_package ; do
	PYMODULES="fpga_dma.py fpga_mgmt.py fpga_pci.py"
	for mod in $PYMODULES ; do
		sudo sed -e "s,PY_BIND_AFI_MGMT_LIBS_DST_DIR,$AFI_MGMT_LIBS_DST_DIR,g" $SDK_DIR/userspace/python_bindings/$mod > $site_package/$mod
		if [[ $? -ne 0 ]] ; then
			echo "Could not install $mod"
			exit 1
		fi
		echo "Installed $site_package/$mod"
	done
done < /tmp/py_install_paths
echo "AWS FPGA: Done with Amazon FPGA Image (AFI) Management Tools install."


#!/bin/bash

#
# Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may
# not use this file except in compliance with the License. A copy of the
# License is located at
#
#     http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
#

# Build script for the Amazon FPGA Image Management Tools and libraries.

TOP=`pwd`

LOGLEVEL=$1
if [ -z "$LOGLEVEL" ]; then
	CONFIG_LOGLEVEL=0
else
	CONFIG_LOGLEVEL=$LOGLEVEL
fi

if allow_non_root ; then
       OPT="$OPT -DFPGA_ALLOW_NON_ROOT=1"
fi

#
# gcc optimizations
#OPT="-O3 -fno-strict-aliasing"

#
# The max number of FPGA BARs that may be attached,
# e.g. (FPGA_SLOT_MAX * FPGA_PF_MAX * FPGA_BAR_PER_PF_MAX) is the upper bound.
#
FPGA_PCI_BARS_DFLT=64
FPGA_PCI_BARS_MAX=$2
if [ -z "$FPGA_PCI_BARS_MAX" ]; then
	FPGA_PCI_BARS_MAX=$FPGA_PCI_BARS_DFLT
else
	FPGA_PCI_BARS_MAX=$FPGA_PCI_BARS_MAX
fi

# get the HDK/SDK version number
source $TOP/../../hdk/hdk_version.txt

function build_exec {
	cd $TOP/$BUILD_DIR
	echo "Entering $TOP/$BUILD_DIR"
	RET=$?
	if [ $RET -ne 0 ]; then
		echo "could not cd to $TOP/$BUILD_DIR"
		exit 1
	fi
	make clean
	RET=$?
	if [ $RET -ne 0 ]; then
		echo "make clean failed"
		exit 1
	fi
	make OPT="$OPT -DCONFIG_LOGLEVEL="$CONFIG_LOGLEVEL" -DFPGA_PCI_BARS_MAX="$FPGA_PCI_BARS_MAX" -DCLI_VERSION='\"$HDK_VERSION\"'"
	RET=$?
	if [ $RET -ne 0 ]; then
		echo "make failed"
		exit 1
	fi
	cd $TOP
}

BUILD_DIR="utils"
build_exec

BUILD_DIR="fpga_libs/fpga_pci"
build_exec

BUILD_DIR="fpga_libs/fpga_dma"
build_exec

BUILD_DIR="fpga_libs/fpga_mgmt"
build_exec

BUILD_DIR="fpga_mgmt_tools/src"
build_exec


#!/bin/bash

#
# Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may
# not use this file except in compliance with the License. A copy of the
# License is located at
#
#     http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
#

# Build script for the Amazon FPGA Image Management Tools and associated libraries.

TOP=`pwd`

LOGLEVEL=$1
if [ -z "$LOGLEVEL" ]; then
	CONFIG_LOGLEVEL=3
else
	CONFIG_LOGLEVEL=$LOGLEVEL
fi

function build_exec {
	cd $TOP/$BUILD_DIR
	echo "Entering $TOP/$BUILD_DIR"
	RET=$?
	if [ $RET -ne 0 ]; then
		echo "could not cd to $TOP/$BUILD_DIR"
		exit 1
	fi
	make clean
	RET=$?
	if [ $RET -ne 0 ]; then
		echo "make clean failed"
		exit 1
	fi
	cd $TOP
}

BUILD_DIR="utils"
build_exec

BUILD_DIR="fpga_libs/fpga_pci"
build_exec

BUILD_DIR="fpga_libs/fpga_mgmt"
build_exec

BUILD_DIR="fpga_mgmt_tools/src"
build_exec


# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

info_msg "Setting up environment variables"

# Make sure that AWS_FPGA_REPO_DIR is set to the location of this script.
if [[ ":$AWS_FPGA_REPO_DIR" == ':' ]]; then
  debug_msg "AWS_FPGA_REPO_DIR not set so setting to $script_dir"
  export AWS_FPGA_REPO_DIR=$script_dir
elif [[ $AWS_FPGA_REPO_DIR != $script_dir ]]; then
  info_msg "Changing AWS_FPGA_REPO_DIR from $AWS_FPGA_REPO_DIR to $script_dir"
  export AWS_FPGA_REPO_DIR=$script_dir
else
  debug_msg "AWS_FPGA_REPO_DIR=$AWS_FPGA_REPO_DIR"
fi

# HDK
# Clear environment variables
unset HDK_DIR
unset HDK_COMMON_DIR
unset HDK_SHELL_DIR
unset HDK_SHELL_DESIGN_DIR

export -f allow_non_root
export -f allow_others

if  allow_non_root || allow_others ; then
	export AWS_FPGA_SDK_GROUP=${AWS_FPGA_SDK_GROUP:-"fpgauser"}
	export SDK_NON_ROOT_USER=$(whoami)
  info_msg "Allowing group ${AWS_FPGA_SDK_GROUP} access to FPGA management tools and resources"
fi

export HDK_DIR=$AWS_FPGA_REPO_DIR/hdk

# The next variable should not be modified and should always point to the /common directory under HDK_DIR
export HDK_COMMON_DIR=$HDK_DIR/common

# Point to the latest version of AWS shell
export HDK_SHELL_DIR=$(readlink -f $HDK_COMMON_DIR/shell_stable)

# Set the common shell design dir
export HDK_SHELL_DESIGN_DIR=$HDK_SHELL_DIR/design

# SDK
unset SDK_DIR

export SDK_DIR=$AWS_FPGA_REPO_DIR/sdk

# SDACCEL
# Setup Location of SDACCEL_DIR
export SDACCEL_DIR=$AWS_FPGA_REPO_DIR/SDAccel
#  Vitis
# Setup Location of VITIS_DIR
export VITIS_DIR=$AWS_FPGA_REPO_DIR/Vitis

# PYTHONPATH
# Update PYTHONPATH with libraries used for unit testing
python_lib=$AWS_FPGA_REPO_DIR/shared/lib
PYTHONPATH=$python_lib:$PYTHONPATH
export PYTHONPATH

# PATH Changes

export PATH=$(echo $PATH | sed -e 's/\(^\|:\)[^:]\+\/shared\/bin\/scripts\(:\|$\)/:/g; s/^://; s/:$//')
PATH=$AWS_FPGA_REPO_DIR/shared/bin/scripts:$PATH

# Enable xilinx licensing
export XILINX_ENABLE_AWS_WHITELIST=095707098027


# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

function info_msg {
  echo -e "INFO: $1"
}

function debug_msg {
    if [[ $debug == 0 ]]; then
        return
    fi
    echo -e "DEBUG: $1"
}

function err_msg {
    echo -e >&2 "ERROR: $1"
}

function warn_msg {
    echo -e "WARNING: $1"
}

function is_myvivado_set {
    if env | grep -q ^MYVIVADO=
    then
        true
    else
        false
    fi
}

function is_xilinx_path_set {
    if env | grep -q ^XILINX_PATH
    then
        true
    else
        false
    fi
}

# Function to check whether a command exists.
exists() {
    if command -v $1 >/dev/null 2>&1
    then
        return 0
    else
        return 1
    fi
}

function get_base_vivado_version {
    local  __resultvar=$1

    if is_myvivado_set
    then

        local MYVIVADO_ENV_VAR_BACKUP=$MYVIVADO

        unset MYVIVADO
        local __vivado_version=$(get_vivado_version)
        export MYVIVADO=$MYVIVADO_ENV_VAR_BACKUP
    elif is_xilinx_path_set
    then
        local XILINX_PATH_ENV_VAR_BACKUP=$XILINX_PATH
        unset XILINX_PATH
        local __vivado_version=$(get_vivado_version)
        export XILINX_PATH=$XILINX_PATH_ENV_VAR_BACKUP
    else
        local __vivado_version=$(get_vivado_version)
    fi

    if [[ "$__resultvar" ]]; then
        eval $__resultvar="'$__vivado_version'"
    else
        echo "$__vivado_version"
    fi

}

function munge_myvivado_var {
    if [[ ! -z $1 ]]; then
        if ! echo "$MYVIVADO" | /bin/grep -Eq "(^|:)$1($|:)" ; then
            if [ "$2" = "after" ] ; then
                MYVIVADO="$MYVIVADO:$1"
            else
                MYVIVADO="$1:$MYVIVADO"
            fi
        fi
        export MYVIVADO
    fi
}

function get_vivado_version {
    local __resultvar=$1

    local __vivado_version=`vivado -version | grep Vivado | head -1`

    if [[ "$__resultvar" ]]; then
        eval $__resultvar="'__$vivado_version'"
    else
        echo "$__vivado_version"
    fi
}

function setup_patches {
    local caller_script="${BASH_SOURCE[1]}"

    info_msg "Checking if patch AR71715 needs to be installed"
    patch_AR71715

    info_msg "Checking if patch AR73068 needs to be installed"
    patch_AR73068 "$caller_script"
}

function is_patch_applied {
    local patch_name="$1"
    local long_vivado_version=$(get_vivado_version)

    if [[ "$long_vivado_version" =~ .*"$patch_name".* ]]; then
      true
    else
      false
    fi
}

function patch_AR71715 {
    local bucket="aws-fpga-developer-ami/1.5.0/Patches"
    local object="AR71715.zip"
    local patch_dirname="AR71715"
    local patch_root="$XILINX_SDX/patches"
    local tool_dir="$XILINX_SDX"

    declare -a valid_vivado_versions=( "Vivado v2018.2_AR71275_op (64-bit)"
                                        "Vivado v2018.2.op (64-bit)"
                                        "Vivado v2018.2 (64-bit)"
                                     )

    local base_vivado_version=$(get_base_vivado_version)
    is_patch_valid=false
    for vivado_version in "${valid_vivado_versions[@]}"
    do
        if [ ":$vivado_version" == ":$base_vivado_version" ]; then
            is_patch_valid=true
        fi
    done

    if [ "$is_patch_valid" == "true" ]; then

        info_msg "Patch AR71715 is valid for $base_vivado_version"

        if [ ! -d $patch_root/$patch_dirname ]; then

            info_msg "Downloading the $patch_dirname patch."

            curl -s https://s3.amazonaws.com/$bucket/$object -o $object || { err_msg "Failed to download Patch $object from $bucket/$object"; return 2; }

            sudo mkdir -p $patch_root || { err_msg "Failed to create path $patch_root  you need to have root permissions to install this patch. If you dont have root permissions please contact your system administrator";  return 2; }

            info_msg "Extracting the $patch_dirname patch."

            sudo unzip $object -d $patch_root/$patch_dirname || { err_msg "Failed to unzip $object into: $patch_root/$patch_dirname"; return 2; }
            sudo cp $tool_dir/scripts/ocl/ocl_util.tcl $tool_dir/scripts/ocl/ocl_util.tcl.bkp
            sudo cp -f $patch_root/$patch_dirname/sdx/scripts/ocl/ocl_util.tcl $tool_dir/scripts/ocl/ocl_util.tcl

            rm $object

            chmod -R 755 $patch_root/$patch_dirname
        fi
    fi
}

function install_patch {
    local patch_name="$1"
    local patch_bucket="$2"
    local patch_object="$3"
    local patch_dir_name="${patch_object%.*}"

    if is_patch_applied $patch_name
    then
        info_msg "$patch_name is already applied. Skipping."
    else
        info_msg "Applying $patch_name"
        info_msg "in bucket $patch_bucket"
        info_msg "object $patch_object"

        # Checking if the patches directory exists and making it if it doesn't
        [ -d $script_dir/patches ] || mkdir -p $script_dir/patches

        info_msg "Downloading the $patch_name from $patch_bucket/$patch_object."
        debug_msg "curl -s $patch_bucket/$patch_object -o $script_dir/patches/$patch_object"

        curl -s $patch_bucket/$patch_object -o $script_dir/patches/$patch_object || { err_msg "Failed to download Patch $object from $patch_bucket/$patch_object"; return 2; }

        info_msg "Extracting the $patch_name to $script_dir/patches/$patch_dir_name."

        unzip -q -o $script_dir/patches/$patch_object -d $script_dir/patches/$patch_dir_name  || { err_msg "Failed to extract $script_dir/patches/$patch_object to $script_dir/patches/$patch_dir_name"; return 2; }

        # XILINX_PATH should not have AR73068 at this point.
        info_msg "Appending XILINX_PATH with $script_dir/patches/$patch_dir_name/vivado"

        export XILINX_PATH=$XILINX_PATH:$script_dir/patches/$patch_dir_name/vivado
    fi
}

function fix_patch_vitis_AR73068_2019_2 {
    local patch_object="$1"
    local patch_dir_name="${patch_object%.*}"
    pushd patches/$patch_dir_name

    sed -i '/.*checksum.*/d' ./vivado/data/ip/xilinx/ddr4_v2_2/component.xml
    sed -i 's/coreRevision>73068/coreRevision>8/' ./vivado/data/ip/xilinx/ddr4_v2_2/component.xml
    popd
}

function patch_AR73068_2019_2 {
    info_msg "Patching Vivado/Vitis 2019.2 with Xilinx Patch AR73068"
    local fix_patch="$1"
    local patch_bucket="https://aws-fpga-developer-ami.s3.amazonaws.com/1.8.0/Patches/AR73068"
    local patch_object="AR73068_Vivado_2019_2_preliminary_rev1.zip"

    install_patch "AR73068" "$patch_bucket" "$patch_object"

    if [[ "$fix_patch" == true ]]; then
      info_msg "Fixing Patch AR73068 for Vitis"
      fix_patch_vitis_AR73068_2019_2 "$patch_object"
    fi
}

function patch_AR73068_2019_1 {
    info_msg "Patching Vivado 2019.1 with Xilinx Patch AR73068"

    local patch_bucket="https://aws-fpga-developer-ami.s3.amazonaws.com/1.7.0/Patches/AR73068"
    local patch_object="AR73068_Vivado_2019_1_preliminary_rev1.zip"

    install_patch "AR73068" "$patch_bucket" "$patch_object"
}

function patch_AR73068_2018_3 {
    info_msg "Patching Vivado 2018.3 with Xilinx Patch AR73068"

    local patch_bucket="https://aws-fpga-developer-ami.s3.amazonaws.com/1.6.0/Patches/AR73068"
    local patch_object="AR73068_Vivado_2018_3_preliminary_rev1.zip"

    install_patch "AR73068" "$patch_bucket" "$patch_object"
}

function patch_AR73068_2018_2 {
    info_msg "Patching Vivado 2018.2 with Xilinx Patch AR73068"

    local patch_bucket="https://aws-fpga-developer-ami.s3.amazonaws.com/1.5.0/Patches/AR73068"
    local patch_object="AR73068_Vivado_2018_2_preliminary_rev1.zip"

    install_patch "AR73068" "$patch_bucket" "$patch_object"
}

function patch_AR73068_2017_4 {
    info_msg "Patching Vivado 2017.4 with Xilinx Patch AR73068"

    local patch_bucket="https://aws-fpga-developer-ami.s3.amazonaws.com/1.4.0/Patches/AR73068"
    local patch_object="AR73068_Vivado_2017_4_preliminary_rev2.zip"

    install_patch "AR73068" "$patch_bucket" "$patch_object"
}

function patch_AR73068 {
    local base_vivado_version=$(get_base_vivado_version)
    local caller_script="$1"
    local fix_patch=false

    # Vitis specific changes
    if [[ "$caller_script" =~ "vitis_setup.sh" ]]; then
      info_msg "Patching Vitis with AR73068"
      fix_patch=true
    fi

    if [[ "${base_vivado_version}" =~ "Vivado v2019.2" ]]; then
      info_msg "Patch $patch_name is valid for Vivado $base_vivado_version."
      patch_AR73068_2019_2 "$fix_patch"
    elif [[ "${base_vivado_version}" =~ "Vivado v2019.1" ]]; then
      info_msg "Patch $patch_name is valid for Vivado $base_vivado_version."
      patch_AR73068_2019_1
    elif [[ "${base_vivado_version}" =~ "Vivado v2018.3" ]]; then
      info_msg "Patch $patch_name is valid for Vivado $base_vivado_version."
      patch_AR73068_2018_3
    elif [[ "${base_vivado_version}" =~ "Vivado v2018.2" ]]; then
      info_msg "Patch $patch_name is valid for Vivado $base_vivado_version."
      patch_AR73068_2018_2
    elif [[ "${base_vivado_version}" =~ "Vivado v2017.4" ]]; then
      info_msg "Patch $patch_name is valid for Vivado $base_vivado_version."
      patch_AR73068_2017_4
    else
      info_msg "Patch AR73068 not applicable for Vivado ${base_vivado_version}."
    fi
}

function allow_non_root {
       [ ! -z ${AWS_FPGA_ALLOW_NON_ROOT} ]
}

function allow_others {
       [ ! -z ${AWS_FPGA_SDK_OTHERS} ]
}


# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

# Script must be sourced from a bash shell or it will not work
# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced
# When being run $0 and $_ will be the same.

os_uname=`uname -r`

script=${BASH_SOURCE[0]}
full_script=$(readlink -f $script)
script_name=$(basename $full_script)
script_dir=$(dirname $full_script)

python_versions=(3.6 2.7)

# First install python if it is not installed.
for python_version in ${python_versions[@]}; do
    if [[ $os_uname =~ (amzn2) ]]; then
        python_version = ${python_version:0:1}
    fi

    python=python$python_version
    pip=pip$python_version
    yum_python_package=${python/./}
    if [ ! -e /usr/bin/$python ]; then
        if ! sudo yum -y install $yum_python_package; then
            echo "Error: Install of $yum_python_package failed"
            exit 1
        fi
    fi
done

# Python2 pip is common between OS's. We can use that to install other
if [ ! -e /usr/bin/pip2 ]; then
    if ! sudo yum -y install python2-pip; then
        echo "Error: Install of $yum_python_package failed"
        exit 1
    fi
    sudo pip install -U 'pip<21'
fi

# Install virtualenv
if [ ! -e /usr/bin/virtualenv ]; then
    if ! sudo pip install virtualenv; then
        echo "Error: Install of virtualenv failed"
        exit 1
    fi
fi

# Install virtualenvwrapper
if [ ! -e ~/.local/bin/virtualenvwrapper.sh ]; then
    if ! pip install --user virtualenvwrapper; then
        echo "Error: Install of virtualenvwrapper failed"
        exit 1
    fi
fi

source ~/.local/bin/virtualenvwrapper.sh

# Create virtualenv environments
for python_version in ${python_versions[@]}; do

    if [[ $os_uname =~ (amzn2) ]]
    then
        site_packages=/usr/lib64/python$python_version/site-packages/

        python=python${python_version:0:1}

        mkvirtualenv -r $script_dir/requirements.txt  -p $(which $python) --system-site-packages python${python_version:0:1}

        # Adding the python bindings site packages to path
        add2virtualenv $site_packages
    else
        python=python$python_version
        mkvirtualenv -r $script_dir/requirements.txt  -p $(which $python) python${python_version:0:1}
    fi
done


# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

# Script must be sourced from a bash shell or it will not work
# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced
# When being run $0 and $_ will be the same.

script=${BASH_SOURCE[0]}
if [ $script == $0 ]; then
  echo "ERROR: You must source this script"
  exit 2
fi

full_script=$(readlink -f $script)
script_name=$(basename $full_script)
script_dir=$(dirname $full_script)

if ! source $script_dir/setup_test_env.sh; then
    return 1
fi

if ! source $WORKSPACE/sdaccel_setup.sh; then
    return 1
fi


# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

# Script must be sourced from a bash shell or it will not work
# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced
# When being run $0 and $_ will be the same.

script=${BASH_SOURCE[0]}
if [ $script == $0 ]; then
  echo "ERROR: You must source this script"
  exit 2
fi

full_script=$(readlink -f $script)
script_name=$(basename $full_script)
script_dir=$(dirname $full_script)

if ! source $script_dir/setup_test_env.sh; then
    return 1
fi

if ! source $WORKSPACE/vitis_setup.sh; then
    return 1
fi


# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

# Script must be sourced from a bash shell or it will not work
# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced
# When being run $0 and $_ will be the same.

script=${BASH_SOURCE[0]}
if [ $script == $0 ]; then
  echo "ERROR: You must source this script"
  exit 2
fi

full_script=$(readlink -f $script)
script_name=$(basename $full_script)
script_dir=$(dirname $full_script)

instance_id=`curl http://169.254.169.254/latest/meta-data/instance-id`
instance_type=`curl http://169.254.169.254/latest/meta-data/instance-type`

echo "Test Running on INSTANCE ID: $instance_id INSTANCE TYPE: $instance_type"

if [ ":$WORKSPACE" == ":" ]; then
    export WORKSPACE=$(git rev-parse --show-toplevel)
fi
export WORKON_HOME=$WORKSPACE/.virtualenvs

$script_dir/install_python_venv.sh

# Setup default environment to work on
source $WORKSPACE/.virtualenvs/python2/bin/activate

export PYTHONPATH=$WORKSPACE/shared/lib:$PYTHONPATH

export AWS_DEFAULT_REGION=us-east-1


# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

# Script must be sourced from a bash shell or it will not work
# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced
# When being run $0 and $_ will be the same.

script=${BASH_SOURCE[0]}
if [ $script == $0 ]; then
  echo "ERROR: You must source this script"
  exit 2
fi

full_script=$(readlink -f $script)
script_name=$(basename $full_script)
script_dir=$(dirname $full_script)

if ! source $script_dir/setup_test_env.sh; then
    return 1
fi

if ! source $WORKSPACE/hdk_setup.sh; then
    return 1
fi


# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

# Script must be sourced from a bash shell or it will not work
# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced
# When being run $0 and $_ will be the same.

script=${BASH_SOURCE[0]}
if [ $script == $0 ]; then
  echo "ERROR: You must source this script"
  exit 2
fi

full_script=$(readlink -f $script)
script_name=$(basename $full_script)
script_dir=$(dirname $full_script)

export LD_LIBRARY_PATH=$XILINX_SDX/lnx64/tools/opencv/:$LD_LIBRARY_PATH

if ! source $script_dir/setup_test_env.sh; then
    return 1
fi

if ! source $script_dir/setup_test_xrtpatch.sh; then
    return 1
fi

if ! source $WORKSPACE/sdaccel_setup.sh; then
    return 1
fi


# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

# Script must be sourced from a bash shell or it will not work
# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced
# When being run $0 and $_ will be the same.

script=${BASH_SOURCE[0]}
if [ $script == $0 ]; then
  echo "ERROR: You must source this script"
  exit 2
fi

full_script=$(readlink -f $script)
script_name=$(basename $full_script)
script_dir=$(dirname $full_script)

export LD_LIBRARY_PATH=$XILINX_VITIS/lnx64/tools/opencv/:$LD_LIBRARY_PATH

if ! source $script_dir/setup_test_env.sh; then
    return 1
fi

if ! source $script_dir/setup_test_xrtpatch.sh; then
    return 1
fi

if ! source $WORKSPACE/vitis_setup.sh; then
    return 1
fi


# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

# Script must be sourced from a bash shell or it will not work
# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced
# When being run $0 and $_ will be the same.

script=${BASH_SOURCE[0]}
if [ $script == $0 ]; then
  echo "ERROR: You must source this script"
  exit 2
fi

full_script=$(readlink -f $script)
script_name=$(basename $full_script)
script_dir=$(dirname $full_script)
setup_test_env_script_dir=$script_dir

if ! source $script_dir/setup_test_env.sh; then
  return 1
fi

if ! source $WORKSPACE/sdk_setup.sh; then
  return 1
fi

if [ x$1 == "xpy_bindings" ] ; then
  source $WORKSPACE/.virtualenvs/python3/bin/activate
  aws s3 cp s3://aws-fpga-jenkins-testing/python_bindings_dependencies/setup.sh .
  chmod 755 ./setup.sh
  ./setup.sh
  export PYTHONPATH=$PYTHONPATH:$SDK_DIR/apps
  source $WORKSPACE/.virtualenvs/python2/bin/activate
fi


# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

# Script must be sourced from a bash shell or it will not work
# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced
# When being run $0 and $_ will be the same.

script=${BASH_SOURCE[0]}
if [ $script == $0 ]; then
  echo "ERROR: You must source this script"
  exit 2
fi

full_script=$(readlink -f $script)
script_name=$(basename $full_script)
script_dir=$(dirname $full_script)

s3_ami_bucket=aws-fpga-developer-ami

VIVADO_TOOL_VERSION=`vivado -version | grep Vivado | head -1 | sed 's:Vivado *::' | sed 's: .*$::' | sed 's:v::'`
export VIVADO_TOOL_VERSION=${VIVADO_TOOL_VERSION:0:6}
echo "VIVADO_TOOL_VERSION is $VIVADO_TOOL_VERSION"

if [[ "$VIVADO_TOOL_VERSION" =~ .*2018\.2.* ]]; then
    echo "Xilinx Vivado version is 2018.2"

    s3_ami_version=1.5.0
    xrt_release_version=XRT_2018_2_XDF_RC5
    xrt_rpm_name=xrt_201802.2.1.0_7.5.1804-xrt.rpm
    aws_xrt_rpm_name=xrt_201802.2.1.0_7.5.1804-aws.rpm

    xrt_rpm_path=$s3_ami_bucket/$s3_ami_version/Patches/$xrt_release_version/$xrt_rpm_name
    aws_xrt_rpm_path=$s3_ami_bucket/$s3_ami_version/Patches/$xrt_release_version/$aws_xrt_rpm_name

    if [ -f "/opt/xilinx/xrt/include/version.h" ]; then
       echo "XRT installed. proceeding to check version compatibility"
       xrt_build_ver=$(grep  'xrt_build_version_hash\[\]' /opt/xilinx/xrt/include/version.h | sed 's/";//' | sed 's/^.*"//')
       echo "Installed XRT version hash : $xrt_build_ver"
       if grep -Fxq "$xrt_build_ver" $AWS_FPGA_REPO_DIR/SDAccel/sdaccel_xrt_version.txt
       then
          echo "XRT version $xrt_build_ver is up-to-date."
       else
          echo "$xrt_build_ver is stale. upgrading XRT to"
          cat $AWS_FPGA_REPO_DIR/SDAccel/sdaccel_xrt_version.txt
          curl -s https://s3.amazonaws.com/$xrt_rpm_path  -o $xrt_rpm_name || { echo " Error: Failed to download xrt rpm from  $xrt_rpm_path"; return 2; }
          curl -s https://s3.amazonaws.com/$aws_xrt_rpm_path -o $aws_xrt_rpm_name || { echo " Error: Failed to download aws xrt rpm from  $aws_xrt_rpm_path"; return 2; }
          sudo yum reinstall -y $xrt_rpm_name
          echo " XRT patch rpm installed successfully"
          sudo yum install -y $aws_xrt_rpm_name
          echo " XRT patch aws rpm installed successfully"
       fi
    else
       echo "XRT not installed. Please install XRT"
       curl -s https://s3.amazonaws.com/$xrt_rpm_path  -o $xrt_rpm_name || { echo " Error: Failed to download xrt rpm from  $xrt_rpm_path"; return 2; }
       curl -s https://s3.amazonaws.com/$aws_xrt_rpm_path -o $aws_xrt_rpm_name || { echo " Error: Failed to download aws xrt rpm from  $aws_xrt_rpm_path"; return 2; }
       sudo yum reinstall -y $xrt_rpm_name
       echo " XRT patch rpm installed successfully"
       sudo yum install -y $aws_xrt_rpm_name
       echo " XRT patch aws rpm installed successfully"
    fi
elif [[ "$VIVADO_TOOL_VERSION" =~ .*2018\.3.* ]]; then
    echo "Xilinx Vivado version is 2018.3"

    s3_ami_version=1.6.0
    xrt_release_version=XRT_2018_3_RC5
    xrt_rpm_name=xrt_201830.2.1.0_7.6.1810-xrt.rpm
    aws_xrt_rpm_name=xrt_201830.2.1.0_7.6.1810-aws.rpm

    xrt_rpm_path=$s3_ami_bucket/$s3_ami_version/Patches/$xrt_release_version/$xrt_rpm_name
    aws_xrt_rpm_path=$s3_ami_bucket/$s3_ami_version/Patches/$xrt_release_version/$aws_xrt_rpm_name

    if [ -f "/opt/xilinx/xrt/include/version.h" ]; then
       echo "XRT installed. proceeding to check version compatibility"
       xrt_build_ver=$(grep  'xrt_build_version_hash\[\]' /opt/xilinx/xrt/include/version.h | sed 's/";//' | sed 's/^.*"//')
       echo "Installed XRT version hash : $xrt_build_ver"
       if grep -Fxq "$xrt_build_ver" $AWS_FPGA_REPO_DIR/SDAccel/sdaccel_xrt_version.txt
       then
          echo "XRT version $xrt_build_ver is up-to-date."
       else
          echo "$xrt_build_ver is stale. upgrading XRT to"
          cat $AWS_FPGA_REPO_DIR/SDAccel/sdaccel_xrt_version.txt
          curl -s https://s3.amazonaws.com/$xrt_rpm_path  -o $xrt_rpm_name || { echo " Error: Failed to download xrt rpm from  $xrt_rpm_path"; return 2; }
          curl -s https://s3.amazonaws.com/$aws_xrt_rpm_path -o $aws_xrt_rpm_name || { echo " Error: Failed to download aws xrt rpm from  $aws_xrt_rpm_path"; return 2; }
          sudo yum reinstall -y $xrt_rpm_name
          echo " XRT patch rpm installed successfully"
          sudo yum reinstall -y $aws_xrt_rpm_name
          echo " XRT patch aws rpm installed successfully"
       fi
    else
       echo "XRT not installed. Please install XRT"
       curl -s https://s3.amazonaws.com/$xrt_rpm_path  -o $xrt_rpm_name || { echo " Error: Failed to download xrt rpm from  $xrt_rpm_path"; return 2; }
       curl -s https://s3.amazonaws.com/$aws_xrt_rpm_path -o $aws_xrt_rpm_name || { echo " Error: Failed to download aws xrt rpm from  $aws_xrt_rpm_path"; return 2; }
       sudo yum reinstall -y $xrt_rpm_name
       echo " XRT patch rpm installed successfully"
       sudo yum install -y $aws_xrt_rpm_name
       echo " XRT patch aws rpm installed successfully"
    fi
elif [[ "$VIVADO_TOOL_VERSION" =~ .*2019\.1.* ]]; then
    echo "Xilinx Vivado version is 2019.1"

    s3_ami_version=1.7.0
    xrt_release_version=XRT_2019_1_0_3
    xrt_rpm_name=xrt_201910.2.2.0_7.7.1908-xrt.rpm
    aws_xrt_rpm_name=xrt_201910.2.2.0_7.7.1908-aws.rpm

    xrt_rpm_path=$s3_ami_bucket/$s3_ami_version/Patches/$xrt_release_version/$xrt_rpm_name
    aws_xrt_rpm_path=$s3_ami_bucket/$s3_ami_version/Patches/$xrt_release_version/$aws_xrt_rpm_name

    if [ -f "/opt/xilinx/xrt/include/version.h" ]; then
       echo "XRT installed. proceeding to check version compatibility"
       xrt_build_ver=$(grep  'xrt_build_version_hash\[\]' /opt/xilinx/xrt/include/version.h | sed 's/";//' | sed 's/^.*"//')
       echo "Installed XRT version hash : $xrt_build_ver"
       if grep -Fxq "$xrt_build_ver" $AWS_FPGA_REPO_DIR/SDAccel/sdaccel_xrt_version.txt
       then
          echo "XRT version $xrt_build_ver is up-to-date."
       else
          echo "$xrt_build_ver is stale. upgrading XRT to"
          cat $AWS_FPGA_REPO_DIR/SDAccel/sdaccel_xrt_version.txt
          curl -s https://s3.amazonaws.com/$xrt_rpm_path  -o $xrt_rpm_name || { echo " Error: Failed to download xrt rpm from  $xrt_rpm_path"; return 2; }
          curl -s https://s3.amazonaws.com/$aws_xrt_rpm_path -o $aws_xrt_rpm_name || { echo " Error: Failed to download aws xrt rpm from  $aws_xrt_rpm_path"; return 2; }
          sudo yum reinstall -y $xrt_rpm_name
          echo " XRT patch rpm installed successfully"
          sudo yum reinstall -y $aws_xrt_rpm_name
          echo " XRT patch aws rpm installed successfully"
       fi
    else
       echo "XRT not installed. Please install XRT"
       curl -s https://s3.amazonaws.com/$xrt_rpm_path  -o $xrt_rpm_name || { echo " Error: Failed to download xrt rpm from  $xrt_rpm_path"; return 2; }
       curl -s https://s3.amazonaws.com/$aws_xrt_rpm_path -o $aws_xrt_rpm_name || { echo " Error: Failed to download aws xrt rpm from  $aws_xrt_rpm_path"; return 2; }
       sudo yum reinstall -y $xrt_rpm_name
       echo " XRT patch rpm installed successfully"
       sudo yum install -y $aws_xrt_rpm_name
       echo " XRT patch aws rpm installed successfully"
    fi
else
   echo "Xilinx Vivado version is $VIVADO_TOOL_VERSION . Proceeding with base runtime version "
fi


#
# Copyright (C) 2018 Xilinx, Inc
# Xilinx XRT setup functions
#
# Author: ryan.radjabi@xilinx.com
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may
# not use this file except in compliance with the License. A copy of the
# License is located at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#

XRT_PATH="${VITIS_DIR}/Runtime/XRT_${RELEASE_VER}"

function get_install_cmd {
    xrt_inst_cmd="install"
    aws_inst_cmd="install"
    if [[ $(lsb_release -si) == "Ubuntu" ]]; then
        dpkg -s xrt
        ret=$?
        if [[ $ret == "0" ]]; then
            xrt_inst_cmd="install --reinstall"
        fi
        dpkg -s xrt-aws
        ret=$?
        if [[ $ret == "0" ]]; then
            aws_inst_cmd="install --reinstall"
        fi
    elif [[ $(lsb_release -si) == "CentOS" ]]; then
        rpm -q xrt
        ret=$?
        if [[ $ret == "0" ]]; then
            xrt_inst_cmd="reinstall"
        fi
        rpm -q xrt-aws
        ret=$?
        if [[ $ret == "0" ]]; then
            aws_inst_cmd="reinstall"
        fi
    fi
}

function build_xrt {
    info_msg "xrt-path: $XRT_PATH"
    if [ -z "$(ls -A $XRT_PATH)" ]; then
        # XRT_PATH is empty, this is the first run, so call submodule update
        git submodule update --init -- $XRT_PATH
    else
        # XRT_PATH is not empty, only call init, this allows local changes to exist in XRT
        git submodule init -- $XRT_PATH
    fi
    info_msg "XRT Developer Flow: Building Xilinx runtime XRT..."
    sudo sh -c "cd $XRT_PATH;./src/runtime_src/tools/scripts/xrtdeps.sh;"
    ret=$?
    if [[ $ret != 0 ]]; then
        err_msg "XRT Developer Flow: Failed to install dependencies: xrtdeps.sh: {$?}"
        return $?
    fi
    if [[ $(lsb_release -si) == "CentOS" ]]; then
        scl enable devtoolset-6 "cd ${XRT_PATH}/build/; ./build.sh;"
    elif [[ $(lsb_release -si) == "Ubuntu" ]]; then
        sudo sh -c "cd ${XRT_PATH}/build/; ./build.sh;"
    fi
    ret=$?
    if [[ $ret != 0 ]]; then
        err_msg "XRT Developer Flow: Failed to build XRT: {$?}"
    fi

    return $?
}

# takes the path to RPM/DEB package as argument
function install_xrt_package {
    get_install_cmd
    if [[ $(lsb_release -si) == "CentOS" ]]; then
        sudo sh -c "cd $1; yum ${xrt_inst_cmd} -y xrt_*-xrt.rpm; yum ${aws_inst_cmd} -y xrt_*-aws.rpm;"
    elif [[ $(lsb_release -si) == "Ubuntu" ]]; then
        sudo sh -c "cd $1; apt ${xrt_inst_cmd} ./xrt_*-xrt.deb; apt ${aws_inst_cmd} ./xrt_*-aws.deb;"
    fi
    ret=$?
    if [[ $ret != 0 ]]; then
        err_msg "XRT Developer Flow: Failed to install XRT: {$?}"
    else
        info_msg "Xilinx runtime installed"
    fi
    return $?
}

function setup_runtime {
    if [ -e /opt/xilinx/xrt ]; then # Check if XRT is installed
        info_msg "XRT Install, non-dev"
        export XILINX_XRT=/opt/xilinx/xrt
        export PATH=$PATH:/opt/xilinx/xrt/bin

        export LD_LIBRARY_PATH=$XILINX_XRT/lib:$LD_LIBRARY_PATH

        if [[ $RELEASE_VER =~ .*2019\.2.* ]]; then

          # copy libstdc++ from $XILINX_VITIS/lib
          if [[ $(lsb_release -si) == "Ubuntu" ]]; then
              sudo cp $XILINX_VITIS/lib/lnx64.o/Ubuntu/libstdc++.so* /opt/xilinx/xrt/lib/
          elif [[ $(lsb_release -si) == "CentOS" ]]; then
              sudo cp $XILINX_VITIS/lib/lnx64.o/Default/libstdc++.so* /opt/xilinx/xrt/lib/
          elif [[ $(lsb_release -si) == "Amazon" ]]; then
              sudo cp /lib64/libstdc++.so* /opt/xilinx/xrt/lib/
          else
              info_msg "Unsupported OS."
              return 1
          fi
        fi
    else # No XRT available
        err_msg "Xilinx XRT runtime not installed - This is required if you are running on an F1 instance."
    fi
}


#!/bin/bash

# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
#    http://aws.amazon.com/asl/
#
# or in the "license" file accompanying this file. This file is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
# implied. See the License for the specific language governing permissions and
# limitations under the License.

set -e

script=${BASH_SOURCE[0]}
full_script=$(readlink -f $script)
script_name=$(basename $full_script)

source $AWS_FPGA_REPO_DIR/shared/bin/set_common_functions.sh
source $AWS_FPGA_REPO_DIR/shared/bin/set_common_env_vars.sh
script_dir=$(dirname $full_script)

debug=0

function usage {
   info_msg "USAGE: $script_name [-h|-help] [-s3_bucket=<bucket_name>] [-s3_dcp_key=<S3_folder_of_dcp>] [-s3_logs_key=<S3_folder_of_logs>] [-xclbin=<xclbin_filename>] [-o=<awsxclbin_filename>] [-awsprofile=<aws_profile_name>]"
}

function help {
  info_msg "$script_name"
  info_msg " "
  info_msg "Vitis AFI Creation"
  info_msg " "
  info_msg "create_vitis_afi.sh assumes you have:"
  info_msg "  (*) Read the README on Github and understand the Vitis workflow (Vitis/README.md)"
  info_msg "  (*) Generated an XCLBIN using the Vitis Build flow"
  info_msg "  (*) Ready to create an AFI and test on F1.  Your kernel has been validated using SW/HW Emulation."
  info_msg "create_vitis_afi.sh will:"
  info_msg "  (1) Extract three parts from your XCLBIN:  DCP (.dcp) , clocks data(.json) and build metadata (.json)"
  info_msg "  (2) Generates a Manifest file for AFI creation that sets the clocks based on your achieved target freq from your build"
  info_msg "  (3) Prepares tar file for AFI creation process"
  info_msg "  (4) Calls aws ec2 create-fpga-image"
  info_msg "  (5) Creates new XCLBIN (called AWSXCLBIN) that is composed of: Metadata and AGFI-ID"
  echo " "
  usage
}

if [ "$1" == "" ]
then
    err_msg "Invalid usage"
    usage
    exit 1
fi

while [ "$1" != "" ]; do
    PARAM=`echo $1 | awk -F= '{print $1}'`
    VALUE=`echo $1 | awk -F= '{print $2}'`
    case $PARAM in
        -h | --help)
            help
            exit
            ;;
        -xclbin)
            xclbin=$VALUE
            ;;
        -o)
            awsxclbin=$VALUE
            ;;
        -aws_profile_name)
            aws_profile_name=$VALUE
            ;;
        -s3_bucket)
            s3_bucket=$VALUE
            ;;
        -s3_logs_key)
            s3_logs=$VALUE
            ;;
        -s3_dcp_key)
            s3_dcps=$VALUE
            ;;
        *)
            err_msg "Unknown parameter \"$PARAM\""
            usage
            exit 1
            ;;
    esac
    shift
done

if [ "$RELEASE_VER" == "" ]
then
    err_msg "Env variable RELEASE_VER not set, did you source sdaccel_setup.sh?"
    exit 1
fi

if [[ -e "$xclbin" ]]
then
    info_msg "Found xclbin '$xclbin'"
else
    err_msg "File '$xclbin' not found"
    exit 1
fi

stripped_xclbin=$(basename $xclbin)
ext_xclbin=${stripped_xclbin##*.}
stripped_xclbin=${stripped_xclbin%.*}

info_msg "$stripped_xclbin"

if [ "$awsxclbin" == "" ]
then
    awsxclbin=$stripped_xclbin
fi

if [ "$awsxclbin" != "$stripped_xclbin" ]
then
    warn_msg "$awsxclbin does not match $stripped_xclbin"
    warn_msg "For github examples, -o <xclbin_filename> must be equal to $stripped_xclbin"
fi

if [[ -e "$awsxclbin" ]]
then
    err_msg "File '$awsxclbin' already exists"
    exit 1
fi

if [ ":$s3_bucket" == ":" ]
then
    err_msg "Invalid s3_bucket"
    usage
    exit 1
fi

# s3 logs is not required
# s3 dcp key is required
if [ "$s3_dcps" == "" ]
then
    err_msg "Invalid s3_dcps key"
    usage
    exit 1
fi

timestamp=$(date +"%y_%m_%d-%H%M%S")

#Steps
#1. Strip XCLBIN to get DCP for ingestion
#2. Create Manifest file
#3. Prepare ingestion tar file
#4. Call create-fpga-image
#5. Manipulate the AFI ID
#6. Create awsxclbin

#STEP 1
#Strip XCLBIN to get DCP for ingestion
#/opt/xilinx/xrt/bin/xclbinsplit -o ${timestamp} $xclbin
/opt/xilinx/xrt/bin/xclbinutil --dump-section BUILD_METADATA:JSON:${timestamp}_build.json --dump-section CLOCK_FREQ_TOPOLOGY:JSON:${timestamp}_clocks.json --dump-section BITSTREAM:RAW:${timestamp}_SH_CL_routed.dcp -i $xclbin
if [[ -e "${timestamp}_SH_CL_routed.dcp" ]]
then
    info_msg "Split DCP from xclbin: ${timestamp}_SH_CL_routed.dcp"
else
    err_msg "File ${timestamp}_SH_CL_routed.dcp not found"
    exit 1
fi
if [[ -e "${timestamp}_build.json" ]]
then
    info_msg "The build Metadata from xclbin: ${timestamp}_build.json"
else
    err_msg "File ${timestamp}_build.json not found"
    exit 1
fi
if [[ -e "${timestamp}_clocks.json" ]]
then
    info_msg "The clocks Metadata from xclbin: ${timestamp}_clocks.json"
else
    err_msg "File ${timestamp}_clocks.json not found"
    exit 1
fi

if [[ -d "to_aws" ]]
then
    err_msg "Directory to_aws already exists"
    exit 1
fi

mkdir to_aws
cp ${timestamp}_SH_CL_routed.dcp ./to_aws/

#STEP 2
#Create Manifest file
strategy=DEFAULT
hdk_version=$(grep 'HDK_VERSION' $script_dir/../../hdk/hdk_version.txt | sed 's/=/ /g' | awk '{print $2}')
shell_version=0x04261818
tool_version=v$RELEASE_VER
device_id=0xF010
vendor_id=0x1D0F
subsystem_id=0x1D51
subsystem_vendor_id=0xFEDD
# Get XSA info from build metadata
vendor=$(echo `grep -A 6 dsa ./${timestamp}_build.json | grep vendor | sed 's/.*: "//g' | sed 's/",//'`)
board_id=$(echo `grep -A 6 dsa ./${timestamp}_build.json | grep board_id | sed 's/.*: "//g' | sed 's/",//'`)
plat_name=$(echo `grep -A 6 dsa ./${timestamp}_build.json | grep name | sed 's/.*: "//g' | sed 's/",//'`)
major=$(echo `grep -A 6 dsa ./${timestamp}_build.json | grep major | sed 's/.*: "//g' | sed 's/",//'`)
minor=$(echo `grep -A 6 dsa ./${timestamp}_build.json | grep minor | sed 's/.*: "//g' | sed 's/",//'`)
# Get clock info from clock metadata
clock_main_a0=$(echo `grep -B 1 SYSTEM ${timestamp}_clocks.json | grep -o -e '[0-9]*'`)
clock_extra_b0=$(echo `grep -B 2 DATA_CLK ${timestamp}_clocks.json | grep freq | grep -o -e '[0-9]*'`)
clock_extra_c0=$(echo `grep -B 2 KERNEL_CLK ${timestamp}_clocks.json | grep -o -e '[0-9]*'`)

if [[ "$vendor" != "xilinx" && "$board_id" != "aws-vu9p-f1" && "$plat_name" != "shell-v04261818" && "$major" != "201920" && "$minor" != "2" ]]
then
    err_msg "Platform ${vendor}_${board_id}_${plat_name}_${major}_${minor} used to create xclbin is not correct, you should be using xilinx_aws-vu9p-f1_shell-v04261818_201920_3"
    exit
fi

#Write Manifest File here
hash=$( sha256sum  to_aws/${timestamp}_SH_CL_routed.dcp | awk '{ print $1 }' )
manifest_file="${timestamp}_manifest.txt"
exec 3<>$manifest_file
echo "manifest_format_version=2" >&3
echo "pci_vendor_id=$vendor_id" >&3
echo "pci_device_id=$device_id" >&3
echo "pci_subsystem_id=$subsystem_id" >&3
echo "pci_subsystem_vendor_id=$subsystem_vendor_id" >&3
echo "dcp_hash=$hash" >&3
echo "shell_version=$shell_version" >&3
echo "dcp_file_name=${timestamp}_SH_CL_routed.dcp" >&3
echo "hdk_version=$hdk_version" >&3
echo "tool_version=$tool_version" >&3
echo "date=$timestamp" >&3
echo "clock_main_a0=$clock_main_a0" >&3
echo "clock_extra_b0=$clock_extra_b0" >&3
echo "clock_extra_c0=$clock_extra_c0" >&3
exec 3>&-
exec 3>&-

if [[ -e "$manifest_file" ]]
then
    info_msg "Generated manifest file '$manifest_file'"
else
    err_msg "File '$manifest_file' not found"
    exit 1
fi
cp $manifest_file to_aws/$manifest_file

#STEP 3
#Prepare ingestion
tar -cf ${timestamp}_Developer_Vitis_Kernel.tar to_aws/${timestamp}_SH_CL_routed.dcp to_aws/${timestamp}_manifest.txt
#STEP 4
#Call create-fpga-image
profile_text=""
if [ "$aws_profile_name" != "" ]
then
    profile_text="--profile ${aws_profile_name}"
fi

log_storage_text=""
if [ "${s3_logs}" != "" ]
then
    log_storage_text="--logs-storage-location Bucket=${s3_bucket},Key=${s3_logs}"
fi

aws s3 ${profile_text} cp ${timestamp}_Developer_Vitis_Kernel.tar s3://${s3_bucket}/${s3_dcps}/
aws ec2 ${profile_text} create-fpga-image --name ${stripped_xclbin} --description ${stripped_xclbin} --input-storage-location Bucket=${s3_bucket},Key=${s3_dcps}/${timestamp}_Developer_Vitis_Kernel.tar ${log_storage_text} > ${timestamp}_afi_id.txt

#STEP 5
#Manipulate the AFI ID
test=`grep agfi ${timestamp}_afi_id.txt | awk -F: '{print $2}' | sed 's/ \"//g' | sed 's/\".*//g' | sed ':a;N;$!ba;s/\n/ /g'`
echo -n $test > ${timestamp}_agfi_id.txt
echo ${timestamp}_agfi_id.txt

#STEP 6
#Create .awsxclbin

if [[ "$RELEASE_VER" == "2020.2" || "$RELEASE_VER" == "2021.1" || "$RELEASE_VER" == "2021.2" ]]
then
	/opt/xilinx/xrt/bin/xclbinutil -i $xclbin --remove-section PARTITION_METADATA --replace-section BITSTREAM:RAW:${timestamp}_agfi_id.txt -o ${awsxclbin}.awsxclbin
else
	/opt/xilinx/xrt/bin/xclbinutil -i $xclbin --remove-section PARTITION_METADATA --remove-section SYSTEM_METADATA --replace-section BITSTREAM:RAW:${timestamp}_agfi_id.txt -o ${awsxclbin}.awsxclbin
fi


# Amazon FPGA Hardware Development Kit
#
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0

# Script must be sourced from a bash shell or it will not work
# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced
# When being run $0 and $_ will be the same.

script=${BASH_SOURCE[0]}
if [ $script == $0 ]; then
  echo "ERROR: You must source this script"
  exit 2
fi

full_script=$(readlink -f $script)
script_name=$(basename $full_script)
script_dir=$(dirname $full_script)
current_dir=$(pwd)

debug=0

function usage {
  echo -e "USAGE: source [\$AWS_FPGA_REPO_DIR/]$script_name [-d|-debug] [-h|-help]"
}

function help {
  info_msg "$script_name"
  info_msg " "
  info_msg "Sets up the environment for AWS FPGA HDK tools."
  info_msg " "
  info_msg "hdk_setup.sh script will:"
  info_msg "  (1) Check if Xilinx Vivado is installed,"
  info_msg "  (2) Set up key environment variables HDK_*, and"
  info_msg "  (3) Download/update the HDK shell's checkpoint"
  info_msg "  (4) Prepare DRAM controller and PCIe IP modules if they are not already available in your directory."
  echo " "
  usage
}

# Process command line args
args=( "$@" )
for (( i = 0; i < ${#args[@]}; i++ )); do
  arg=${args[$i]}
  case $arg in
    -d|-debug)
      debug=1
    ;;
    -h|-help)
      help
      return 0
    ;;
    *)
      err_msg "Invalid option: $arg\n"
      usage
      return 1
  esac
done

source $script_dir/shared/bin/set_common_functions.sh
source $script_dir/shared/bin/set_common_env_vars.sh

hdk_shell_version=$(readlink $HDK_COMMON_DIR/shell_stable)

debug_msg "Checking for Vivado install:"

# before going too far make sure Vivado is available
if ! exists vivado; then
    err_msg "Please install/enable Vivado."
    err_msg "  If you are using the FPGA Developer AMI then please request support."
    return 1
fi

# Install any patches as required
info_msg "Setting up Vivado patches if required."
setup_patches

#Searching for Vivado version and comparing it with the list of supported versions

export VIVADO_VER=`vivado -version | grep Vivado | head -1`

info_msg "Using $VIVADO_VER"

if grep -Fxq "$VIVADO_VER" $AWS_FPGA_REPO_DIR/supported_vivado_versions.txt
then
    debug_msg "$VIVADO_VER is supported by this HDK release."
else
    err_msg "$VIVADO_VER is not supported by this HDK release."
    err_msg "Supported versions are:"
    cat $AWS_FPGA_REPO_DIR/supported_vivado_versions.txt
    return 1
fi

VIVADO_TOOL_VERSION=`vivado -version | grep Vivado | head -1 | sed 's:Vivado *::' | sed 's: .*$::'`
export VIVADO_TOOL_VERSION=${VIVADO_TOOL_VERSION:0:7}
echo "VIVADO_TOOL_VERSION is $VIVADO_TOOL_VERSION"

debug_msg "Vivado check succeeded"

# The CL_DIR is where the actual Custom Logic design resides. The developer is expected to override this.
# export CL_DIR=$HDK_DIR/cl/developer_designs

debug_msg "Done setting environment variables.";

# Download correct shell DCP
info_msg "Using HDK shell version $hdk_shell_version"
debug_msg "Checking HDK shell's checkpoint version"
hdk_resources_s3_bucket=aws-fpga-hdk-resources

# Shell files to be downloaded
#declare -a s3_hdk_files=("SH_CL_BB_routed.dcp"
#                         "cl_hello_world.debug_probes.ltx"
#                         "cl_dram_dma.debug_probes.ltx"
#                        )
#
declare -a s3_hdk_files=("SH_CL_BB_routed.dcp"
                        )
#

# Downloading the shell files
for shell_file in "${s3_hdk_files[@]}"
do
  # Determine if shell or debug probe
  if [ $shell_file == "SH_CL_BB_routed.dcp" ]; then
    sub_dir="checkpoints"
  else
    sub_dir="debug_probes"
  fi
  hdk_shell_dir=$HDK_SHELL_DIR/build/$sub_dir/from_aws
  hdk_file=$hdk_shell_dir/$shell_file
  s3_shell_dir=hdk/$hdk_shell_version/build/$sub_dir/from_aws
  aws_alveo_shell_dir=alveo/u200/$hdk_shell_version
  # Download the sha256
  if [ ! -e $hdk_shell_dir ]; then
      mkdir -p $hdk_shell_dir || { err_msg "Failed to create $hdk_shell_dir"; return 2; }
  fi
  # Use curl instead of AWS CLI so that credentials aren't required.
#  echo -n "Do you agree to AWS_F1_Shell_License_Agreement [Y/N]: "
#  read x
#  if [ "$x" != "Y" ]; then
#    echo "exiting hdk_setup"
#    return 2
#  fi
  debug_msg "curl -s https://$hdk_resources_s3_bucket.s3.amazonaws.com/$aws_alveo_shell_dir/$shell_file.sha256 -o $hdk_file.sha256"
  curl -s https://$hdk_resources_s3_bucket.s3.amazonaws.com/$aws_alveo_shell_dir/$shell_file.sha256 -o $hdk_file.sha256 || { err_msg "Failed to download HDK shell's $shell_file version from $aws_alveo_shell_dir/$shell_file.sha256 -o $hdk_file.sha256"; return 2; }
  if grep -q '<?xml version' $hdk_file.sha256; then
     err_msg "Failed to download HDK shell's $shell_file version from $aws_alveo_shell_dir/$shell_file.sha256"
     cat $hdk_file.sha256
     return 2
  fi
  exp_sha256=$(cat $hdk_file.sha256)
  debug_msg "  $shell_file latest   version=$exp_sha256"
  # If shell file already downloaded check its sha256
  if [ -e $hdk_file ]; then
    act_sha256=$( sha256sum $hdk_file | awk '{ print $1 }' )
    debug_msg "  $shell_file existing version=$act_sha256"
    if [[ $act_sha256 != $exp_sha256 ]]; then
      info_msg "HDK shell's $shell_file version is incorrect"
      info_msg "  Saving old file to $hdk_file.back"
      mv $hdk_file $hdk_file.back
    fi
  else
    info_msg "HDK shell's $shell_file hasn't been downloaded yet."
  fi
  if [ ! -e $hdk_file ]; then
    echo -n "Do you agree to AWS_F1_Shell_License_Agreement [Y/N]: "
    read x
    if [ "$x" != "Y" ]; then
      echo "exiting hdk_setup"
      return 2
    fi
    info_msg "Downloading latest HDK shell $shell_file from $aws_alveo_shell_dir/$shell_file"
    # Use curl instead of AWS CLI so that credentials aren't required.
    curl -s https://$hdk_resources_s3_bucket.s3.amazonaws.com/$aws_alveo_shell_dir/$shell_file -o $hdk_file || { err_msg "HDK shell checkpoint download failed"; return 2; }
  fi

  # Check sha256
  act_sha256=$( sha256sum $hdk_file | awk '{ print $1 }' )
  if [[ $act_sha256 != $exp_sha256 ]]; then
    err_msg "Incorrect HDK shell checkpoint version:"
    err_msg "  expected version=$exp_sha256"
    err_msg "  actual   version=$act_sha256"
    err_msg "  There may be an issue with the uploaded checkpoint or the download failed."
    return 2
  fi
  info_msg "HDK shell is up-to-date"
done

# Create DDR and PCIe IP models and patch PCIe
models_dir=$HDK_COMMON_DIR/verif/models
ddr4_model_dir=$models_dir/ddr4_model
if [ -f $ddr4_model_dir/arch_defines.v ]; then
  # Models already built
  # Check to make sure they were built with this version of vivado
  if [[ -f $models_dir/.vivado_version ]]; then
    models_vivado_version=$(cat $models_dir/.vivado_version)
    info_msg "DDR4 model files in $ddr4_model_dir/ were built with $models_vivado_version"
    if [[ $models_vivado_version != $VIVADO_VER ]]; then
      info_msg "  Wrong vivado version so rebuilding with $VIVADO_VER"
    fi
  else
    models_vivado_version=UNKNOWN
    info_msg "DDR4 model files in $ddr4_model_dir/ were built with UNKNOWN Vivado version so rebuilding."
  fi
else
  # Models haven't been built
  models_vivado_version=NOT_BUILT
  info_msg "DDR4 model files in "$ddr4_model_dir/" do NOT exist. Running model creation step.";
fi
if [[ $models_vivado_version != $VIVADO_VER ]] && [ ! -e $models_dir/build.lock ]; then
  rm -rf $HDK_COMMON_DIR/verif/scripts/.done 2>&1 >/dev/null
fi
ddr4_build_dir=$HDK_COMMON_DIR/verif/scripts/tmp
if [ -d $ddr4_build_dir ] && [ ! -e $models_dir/build.lock ]; then rm -rf $ddr4_build_dir; fi
if ! make -s -C $HDK_DIR/common/verif/scripts MODEL_DIR=$models_dir; then
  err_msg "  build dir=$ddr4_build_dir"
  return 2
fi

if [[ ":$CL_DIR" == ':' ]]; then
  info_msg "attention: don't forget to set the CL_DIR variable for the directory of your custom logic.";
else
  info_msg "CL_DIR is $CL_DIR"
  if [ ! -d $CL_DIR ]; then
    err_msg "CL_DIR doesn't exist. set CL_DIR to a valid directory."
    unset CL_DIR
  fi
fi

cd $current_dir

info_msg "AWS HDK setup PASSED.";


# Amazon FPGA Hardware Development Kit
#
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0


#
# Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may
# not use this file except in compliance with the License. A copy of the
# License is located at
#
#     http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
#

# Script must be sourced from a bash shell or it will not work
# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced
# When being run $0 and $_ will be the same.
script=${BASH_SOURCE[0]}
if [ $script == $0 ]; then
  echo "ERROR: You must source this script"
  exit 2
fi

full_script=$(readlink -f $script)
script_name=$(basename $full_script)
script_dir=$(dirname $full_script)
current_dir=$(pwd)

source $script_dir/shared/bin/set_common_functions.sh
source $script_dir/shared/bin/set_common_env_vars.sh

sudo rm -f /tmp/sdk_root_env.exp
typeset -f allow_non_root > /tmp/sdk_root_env.exp
echo "export AWS_FPGA_SDK_GROUP=${AWS_FPGA_SDK_GROUP}" >> /tmp/sdk_root_env.exp
echo "export AWS_FPGA_SDK_OTHERS=${AWS_FPGA_SDK_OTHERS}" >> /tmp/sdk_root_env.exp
echo "export SDK_NON_ROOT_USER=${SDK_NON_ROOT_USER}" >> /tmp/sdk_root_env.exp
echo "export AWS_FPGA_SDK_OVERRIDE_GROUP=${AWS_FPGA_SDK_OVERRIDE_GROUP}" >> /tmp/sdk_root_env.exp
sudo chown root:root /tmp/sdk_root_env.exp
sudo chmod 700 /tmp/sdk_root_env.exp

#
# Execute sdk_install.sh inside a subshell so the user's current
# shell does not exit on errors from the install.
#
cd $script_dir
if ! bash $SDK_DIR/sdk_install.sh; then
    echo "Error: AWS SDK install was unsuccessful, sdk_install.sh returned $?"
    return 1
fi

cd $current_dir
info_msg "$script_name PASSED"


#!/bin/bash

# Amazon FPGA Hardware Development Kit
#
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0

# TODO
# Check if /build and /design directories exist, abort
# Check if $HDK_COMMON_DIR exist

cp -rL $HDK_SHELL_DIR/new_cl_template/build .
cp -r  $HDK_SHELL_DIR/new_cl_template/design .


#!/bin/bash

# Amazon FPGA Hardware Development Kit
#
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0

# Usage help
function usage
{
    echo "usage: aws_build_bit_from_cl.sh [ [-script <vivado_script>] | [-strategy BASIC | DEFAULT | EXPLORE | TIMING | CONGESTION] [-clock_recipe_a A0 | A1 | A2] [-clock_recipe_b B0 | B1 | B2 | B3 | B4 | B5] [-clock_recipe_c C0 | C1 | C2 | C3] [-uram_option 2 | 3 | 4] [-vdefine macro1,macro2,macro3,.....,macrox] -foreground] [-notify] | [-h] | [-H] | [-help] ]"
    echo " "
    echo "By default the build is run in the background using nohup so that the"
    echo "process will not be terminated if the terminal window is closed."
    echo "The window can be closed if it is running on your computer and the"
    echo "network connection is lost. All build output will be redirected to a"
    echo "log file called *.nohup.out."
    echo " "
    echo "The -foreground option runs the build in the foreground. All output will"
    echo "go to the terminal and the build may be terminated if the terminal"
    echo "is closed. This option is useful if you want to wait for the build"
    echo "to complete. This option is safe if the terminal is running on the"
    echo "AWS instance, for example on a GUI desktop on the instance."
}

# Default arguments for script and strategy
strategy=DEFAULT
clock_recipe_a=A0
clock_recipe_b=B0
clock_recipe_c=C0
vivado_script="create_dcp_from_cl.tcl"
foreground=0
notify=0
ignore_memory_requirement=0
expected_memory_usage=30000000
uram_option=2
vdefine=""

function info_msg {
  echo -e "INFO: $1"
}

function debug_msg {
  if [[ $debug == 0 ]]; then
    return
  fi
  echo -e "DEBUG: $1"
}

function warn_msg {
  echo -e "WARNING: $1"
}

function err_msg {
  echo -e >&2 "ERROR: $1"
}

function get_instance_memory {
  local mem=$(awk -F"[: ]+" '/MemTotal/ {print $2;exit}' /proc/meminfo)
  echo "$mem"
}

# Parse command-line arguments
while [ "$1" != "" ]; do
    case $1 in
        -script )               shift
                                vivado_script=$1
                                ;;
        -strategy )             shift
                                strategy=$1
                                ;;
        -clock_recipe_a )       shift
                                clock_recipe_a=$1
                                ;;
        -clock_recipe_b )       shift
                                clock_recipe_b=$1
                                ;;
        -clock_recipe_c )       shift
                                clock_recipe_c=$1
                                ;;
        -uram_option )          shift
                                uram_option=$1
                                ;;
        -vdefine )              shift
                                vdefine=$1
                                ;;
        -foreground )           foreground=1
                                ;;
        -notify )               notify=1
                                ;;
        -ignore_memory_requirement) ignore_memory_requirement=1
                                ;;
        -h | -H | -help )       usage
                                exit
                                ;;
        * )                     usage
                                exit 1
    esac
    shift
done

# Check that script exists
if ! [ -f "$vivado_script" ]; then
  err_msg "$vivado_script doesn't exist."
  exit 1
fi

# Check that strategy is valid
shopt -s extglob
if [[ $strategy != @(BASIC|DEFAULT|EXPLORE|TIMING|CONGESTION) ]]; then
  err_msg "$strategy isn't a valid strategy. Valid strategies are BASIC, DEFAULT, EXPLORE, TIMING and CONGESTION."
  exit 1
fi

# Check that clock_recipe_a is valid
shopt -s extglob
if [[ $clock_recipe_a != @(A0|A1|A2) ]]; then
  err_msg "$clock_recipe_a isn't a valid Clock Group A recipe. Valid Clock Group A recipes are A0, A1, and A2."
  exit 1
fi

# Check that clock_recipe_b is valid
shopt -s extglob
if [[ $clock_recipe_b != @(B0|B1|B2|B3|B4|B5) ]]; then
  err_msg "$clock_recipe_b isn't a valid Clock Group B recipe. Valid Clock Group B recipes are B0, B1, B2, B3, B4, and B5."
  exit 1
fi

# Check that clock_recipe_c is valid
shopt -s extglob
if [[ $clock_recipe_c != @(C0|C1|C2|C3) ]]; then
  err_msg "$clock_recipe_c isn't a valid Clock Group C recipe. Valid Clock Group C recipes are C0, C1, C2, and C3."
  exit 1
fi

# Check that uram_option is valid
shopt -s extglob
if [[ $uram_option != @(2|3|4) ]]; then
  err_msg "$uram_option isn't a valid URAM option. Valid URAM options are 2 (50%), 3 (75%), and 4 (100%)."
  exit 1
fi
# process vdefines
info_msg "VDEFINE is : $vdefine"
shopt -s extglob
IFS=',' read -r -a vdefine_array <<< "$vdefine"

opt_vdefine=""

for index in "${!vdefine_array[@]}"
do
 echo "$index ${vdefine_array[index]}"
 opt_vdefine+=" -verilog_define "
 opt_vdefine+=${vdefine_array[index]}
done
echo "$opt_vdefine"
if [ $expected_memory_usage -gt `get_instance_memory` ]; then

    output_message="YOUR INSTANCE has less memory than is necessary for certain builds. This means that your builds will take longer than expected. \nTo change to an instance type with more memory, please check our instance resize guide: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html"

  if [[ $ignore_memory_requirement == 0 ]]; then
      err_msg "$output_message"
      err_msg "To ignore this memory requirement, run this script again with -ignore_memory_requirement as an argument."
      exit 1
  else
      warn_msg "$output_message"
  fi
fi

info_msg "Starting the design checkpoint build process"
info_msg "Checking for proper environment variables and build directories"

if ! [ $HDK_SHELL_DIR ]
then
	err_msg "HDK_SHELL_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository."
	exit 1
fi

if ! [ $CL_DIR ]
then
	err_msg "CL_DIR environment variable is not set. Set CL_DIR to a valid directory."
	exit 1
fi

if ! [ $HDK_DIR ]
then
	err_msg "HDK_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository."
	exit 1
fi

if ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]
then
	info_msg "prepare_build_env.sh script is not eXecutable, trying to apply chmod +x"
	chmod +x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh
	if ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]
	then
		err_msg "Failed to change prepare_build_environment.sh to eXecutable, aborting!"
		exit 1
	fi
fi

$HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh

if ! [[ $? -eq 0 ]]
then
	err_msg "Missing environment variable or unable to create the needed build directories, aborting!"
	exit 1
fi

# Use timestamp for logs and output files
timestamp=$(date +"%y_%m_%d-%H%M%S")
logname=$timestamp.vivado.log
ln -s -f $logname last_log

info_msg "Environment variables and directories are present. Checking for Vivado installation."

# Before going too far make sure Vivado is available
vivado -version >/dev/null 2>&1 || { err_msg "Please install/enable Vivado." ; return 1; }

# Get the HDK Version
hdk_version=$(grep 'HDK_VERSION' $HDK_DIR/hdk_version.txt | sed 's/=/ /g' | awk '{print $2}')

# Get the Shell Version
shell_version=$(grep 'SHELL_VERSION' $HDK_SHELL_DIR/shell_version.txt | sed 's/=/ /g' | awk '{print $2}')

# Get the PCIe Device & Vendor ID from ID0
id0_version=$(grep -v '^\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID0' | grep 'define' | sed 's/_//g' | awk -F "h" '{print $2}')
device_id="0x${id0_version:0:4}";
vendor_id="0x${id0_version:4:4}";

# Get the PCIe Subsystem & Subsystem Vendor ID from ID1
id1_version=$(grep -v '^\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID1' | grep 'define' | sed 's/_//g' | awk -F "h" '{print $2}')
subsystem_id="0x${id1_version:0:4}";
subsystem_vendor_id="0x${id1_version:4:4}";

# Run vivado
cmd="vivado -mode batch -nojournal -log $logname -source $vivado_script -tclargs $timestamp $strategy $hdk_version $shell_version $device_id $vendor_id $subsystem_id $subsystem_vendor_id $clock_recipe_a $clock_recipe_b $clock_recipe_c $uram_option $notify $opt_vdefine"
if [[ "$foreground" == "0" ]]; then
  nohup $cmd > $timestamp.nohup.out 2>&1 &

  info_msg "Build through Vivado is running as background process, this may take few hours."
  info_msg "Output is being redirected to $timestamp.nohup.out"
  info_msg "If you have set your EMAIL environment variable and -notify is specified, you will receive a notification when complete."
  info_msg "  (See \$HDK_DIR/cl/examples/README.md for details)"
else
  info_msg "Build through Vivado is running in the foreground, this may take a few hours."
  info_msg "The build may be terminated if the network connection to this terminal window is lost."
  $cmd
fi


#!/bin/bash

# Amazon FPGA Hardware Development Kit
#
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0

function info_msg {
  echo -e "INFO: $1"
}

function debug_msg {
  if [[ $debug == 0 ]]; then
    return
  fi
  echo -e "DEBUG: $1"
}

function warn_msg {
  echo -e "WARNING: $1"
}

function err_msg {
  echo -e >&2 "ERROR: $1"
}

if ! [[ $CL_DIR ]]
then
	err_msg "Environment variable CL_DIR is not defined"
	exit 1
fi

if ! [[ $HDK_SHELL_DIR ]]
then
	err_msg "Environment variable HDK_SHELL_DIR is not defined"
	exit 1
fi

if ! [ -d $CL_DIR/build/constraints ]
then
	err_msg "Constraints directory is not found in $CL_DIR/build/ directory"
	exit 1
fi

if ! [ -d $CL_DIR/build/reports ]
then
	info_msg "Creating the reports directory"
	mkdir $CL_DIR/build/reports
	if ! [ -d $CL_DIR/build/reports ]
	then
		err_msg "Failed to create reports directory, please check directory permissions"
		exit 1
	fi
fi

if ! [ -d $CL_DIR/build/checkpoints ]
then
        info_msg "Creating the checkpoints directory"
        mkdir $CL_DIR/build/checkpoints
        if ! [ -d $CL_DIR/build/checkpoints ]
        then
                err_msg "Failed to create checkpoints directory, please check directory permissions"
                exit 1
        fi
fi

if ! [ -d $CL_DIR/build/checkpoints/to_aws ]
then
        info_msg "Creating the checkpoints/to_aws directory"
        mkdir $CL_DIR/build/checkpoints/to_aws
        if ! [ -d $CL_DIR/build/checkpoints/to_aws ]
        then
                err_msg "Failed to create directory, please check directory permissions"
                exit 1
        fi
fi

if ! [ -d $CL_DIR/build/src_post_encryption ]
then
        info_msg "Creating the src_port_encryption directory"
        mkdir $CL_DIR/build/src_post_encryption
        if ! [ -d $CL_DIR/build/src_post_encryption ]
        then
                err_msg "Failed to create directory, please check directory permissions"
                exit 1
        fi
fi

if ! [ -d $CL_DIR/build/bitstreams ]
then
        info_msg "Creating the bitstreams directory"
        mkdir $CL_DIR/build/bitstreams
        if ! [ -d $CL_DIR/build/bitstreams ]
        then
                err_msg "Failed to create bitstreams directory, please check directory permissions"
                exit 1
        fi
fi


#!/bin/bash -f
#*********************************************************************************************************
# Vivado (TM) v2020.2 (64-bit)
#
# Filename    : axi_clock_converter_0.sh
# Simulator   : Aldec Active-HDL Simulator
# Description : Simulation script for compiling, elaborating and verifying the project source files.
#               The script will automatically create the design libraries sub-directories in the run
#               directory, add the library logical mappings in the simulator setup file, create default
#               'do/prj' file, execute compilation, elaboration and simulation steps.
#
# Generated by Vivado on Tue Dec 14 16:44:13 CST 2021
# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020
#
# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved.
#
# usage: axi_clock_converter_0.sh [-help]
# usage: axi_clock_converter_0.sh [-lib_map_path]
# usage: axi_clock_converter_0.sh [-noclean_files]
# usage: axi_clock_converter_0.sh [-reset_run]
#
# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the
# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the
# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch
# that points to these libraries and rerun export_simulation. For more information about this switch please
# type 'export_simulation -help' in the Tcl shell.
#
# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this
# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when
# executing this script. Please type 'axi_clock_converter_0.sh -help' for more information.
#
# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'
#
#*********************************************************************************************************

# Script info
echo -e "axi_clock_converter_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\n"

# Main steps
run()
{
  check_args $# $1
  setup $1 $2
  compile
  simulate
}

# RUN_STEP: <compile>
compile()
{
  # Compile design files
  source compile.do 2>&1 | tee -a compile.log

}

# RUN_STEP: <simulate>
simulate()
{
  runvsimsa -l simulate.log -do "do {simulate.do}"
}

# STEP: setup
setup()
{
  case $1 in
    "-lib_map_path" )
      if [[ ($2 == "") ]]; then
        echo -e "ERROR: Simulation library directory path not specified (type \"./axi_clock_converter_0.sh -help\" for more information)\n"
        exit 1
      fi
     map_setup_file $2
    ;;
    "-reset_run" )
      reset_run
      echo -e "INFO: Simulation run files deleted.\n"
      exit 0
    ;;
    "-noclean_files" )
      # do not remove previous data
    ;;
    * )
     map_setup_file $2
  esac

  # Add any setup/initialization commands here:-

  # <user specific commands>

}

# Map library.cfg file
map_setup_file()
{
  file="library.cfg"
  lib_map_path=""
  if [[ ($1 != "") ]]; then
    lib_map_path="$1"
  fi
  if [[ ($lib_map_path != "") ]]; then
    src_file="$lib_map_path/$file"
    if [[ -e $src_file ]]; then
      vmap -link $lib_map_path
    fi
  fi
}

# Delete generated data from the previous run
reset_run()
{
  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)
  for (( i=0; i<${#files_to_remove[*]}; i++ )); do
    file="${files_to_remove[i]}"
    if [[ -e $file ]]; then
      rm -rf $file
    fi
  done
}

# Check command line arguments
check_args()
{
  if [[ ($1 == 1 ) && ($2 != "-lib_map_path" && $2 != "-noclean_files" && $2 != "-reset_run" && $2 != "-help" && $2 != "-h") ]]; then
    echo -e "ERROR: Unknown option specified '$2' (type \"./axi_clock_converter_0.sh -help\" for more information)\n"
    exit 1
  fi

  if [[ ($2 == "-help" || $2 == "-h") ]]; then
    usage
  fi
}

# Script usage
usage()
{
  msg="Usage: axi_clock_converter_0.sh [-help]\n\
Usage: axi_clock_converter_0.sh [-lib_map_path]\n\
Usage: axi_clock_converter_0.sh [-reset_run]\n\
Usage: axi_clock_converter_0.sh [-noclean_files]\n\n\
[-help] -- Print help information for this script\n\n\
[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\n\
using the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\n\n\
[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\n\
from the previous run will be removed. If you don't want to remove the simulator generated files, use the\n\
-noclean_files switch.\n\n\
[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\n\n"
  echo -e $msg
  exit 1
}

# Launch script
run $1 $2


#!/bin/bash -f
#*********************************************************************************************************
# Vivado (TM) v2020.2 (64-bit)
#
# Filename    : axi_clock_converter_0.sh
# Simulator   : Cadence Incisive Enterprise Simulator
# Description : Simulation script for compiling, elaborating and verifying the project source files.
#               The script will automatically create the design libraries sub-directories in the run
#               directory, add the library logical mappings in the simulator setup file, create default
#               'do/prj' file, execute compilation, elaboration and simulation steps.
#
# Generated by Vivado on Tue Dec 14 16:44:13 CST 2021
# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020
#
# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved.
#
# usage: axi_clock_converter_0.sh [-help]
# usage: axi_clock_converter_0.sh [-lib_map_path]
# usage: axi_clock_converter_0.sh [-noclean_files]
# usage: axi_clock_converter_0.sh [-reset_run]
#
# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the
# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the
# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch
# that points to these libraries and rerun export_simulation. For more information about this switch please
# type 'export_simulation -help' in the Tcl shell.
#
# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this
# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when
# executing this script. Please type 'axi_clock_converter_0.sh -help' for more information.
#
# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'
#
#*********************************************************************************************************

# Directory path for design sources and include directories (if any) wrt this path
ref_dir="."

# Override directory with 'export_sim_ref_dir' env path value if set in the shell
if [[ (! -z "$export_sim_ref_dir") && ($export_sim_ref_dir != "") ]]; then
  ref_dir="$export_sim_ref_dir"
fi

# Set the compiled library directory
ref_lib_dir="."

# Command line options
irun_opts="-64bit -v93 -relax -access +rwc -namemap_mixgen"

# Design libraries
design_libs=(axi_infrastructure_v1_1_0 fifo_generator_v13_2_5 axi_clock_converter_v2_1_21 xil_defaultlib)

# Simulation root library directory
sim_lib_dir="ies_lib"

# Script info
echo -e "axi_clock_converter_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\n"

# Main steps
run()
{
  check_args $# $1
  setup $1 $2
  execute
}

# RUN_STEP: <execute>
execute()
{
  irun $irun_opts \
       -reflib "$ref_lib_dir/unisim:unisim" \
       -reflib "$ref_lib_dir/unisims_ver:unisims_ver" \
       -reflib "$ref_lib_dir/secureip:secureip" \
       -reflib "$ref_lib_dir/unimacro:unimacro" \
       -reflib "$ref_lib_dir/unimacro_ver:unimacro_ver" \
       -top xil_defaultlib.axi_clock_converter_0 \
       -f run.f \
       -top glbl \
       glbl.v \
       +incdir+"$ref_dir/../../../ipstatic/hdl" \
       +incdir+"../../../ipstatic/hdl"
}

# STEP: setup
setup()
{
  case $1 in
    "-lib_map_path" )
      if [[ ($2 == "") ]]; then
        echo -e "ERROR: Simulation library directory path not specified (type \"./axi_clock_converter_0.sh -help\" for more information)\n"
        exit 1
      else
        ref_lib_dir=$2
      fi
    ;;
    "-reset_run" )
      reset_run
      echo -e "INFO: Simulation run files deleted.\n"
      exit 0
    ;;
    "-noclean_files" )
      # do not remove previous data
    ;;
    * )
  esac

  create_lib_dir

  # Add any setup/initialization commands here:-

  # <user specific commands>

}

# Create design library directory paths
create_lib_dir()
{
  if [[ -e $sim_lib_dir ]]; then
    rm -rf $sim_lib_dir
  fi

  for (( i=0; i<${#design_libs[*]}; i++ )); do
    lib="${design_libs[i]}"
    lib_dir="$sim_lib_dir/$lib"
    if [[ ! -e $lib_dir ]]; then
      mkdir -p $lib_dir
    fi
  done
}

# Delete generated data from the previous run
reset_run()
{
  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)
  for (( i=0; i<${#files_to_remove[*]}; i++ )); do
    file="${files_to_remove[i]}"
    if [[ -e $file ]]; then
      rm -rf $file
    fi
  done

  create_lib_dir
}

# Check command line arguments
check_args()
{
  if [[ ($1 == 1 ) && ($2 != "-lib_map_path" && $2 != "-noclean_files" && $2 != "-reset_run" && $2 != "-help" && $2 != "-h") ]]; then
    echo -e "ERROR: Unknown option specified '$2' (type \"./axi_clock_converter_0.sh -help\" for more information)\n"
    exit 1
  fi

  if [[ ($2 == "-help" || $2 == "-h") ]]; then
    usage
  fi
}

# Script usage
usage()
{
  msg="Usage: axi_clock_converter_0.sh [-help]\n\
Usage: axi_clock_converter_0.sh [-lib_map_path]\n\
Usage: axi_clock_converter_0.sh [-reset_run]\n\
Usage: axi_clock_converter_0.sh [-noclean_files]\n\n\
[-help] -- Print help information for this script\n\n\
[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\n\
using the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\n\n\
[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\n\
from the previous run will be removed. If you don't want to remove the simulator generated files, use the\n\
-noclean_files switch.\n\n\
[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\n\n"
  echo -e $msg
  exit 1
}

# Launch script
run $1 $2


#!/bin/bash -f
#*********************************************************************************************************
# Vivado (TM) v2020.2 (64-bit)
#
# Filename    : axi_clock_converter_0.sh
# Simulator   : Mentor Graphics ModelSim Simulator
# Description : Simulation script for compiling, elaborating and verifying the project source files.
#               The script will automatically create the design libraries sub-directories in the run
#               directory, add the library logical mappings in the simulator setup file, create default
#               'do/prj' file, execute compilation, elaboration and simulation steps.
#
# Generated by Vivado on Tue Dec 14 16:44:13 CST 2021
# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020
#
# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved.
#
# usage: axi_clock_converter_0.sh [-help]
# usage: axi_clock_converter_0.sh [-lib_map_path]
# usage: axi_clock_converter_0.sh [-noclean_files]
# usage: axi_clock_converter_0.sh [-reset_run]
#
# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the
# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the
# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch
# that points to these libraries and rerun export_simulation. For more information about this switch please
# type 'export_simulation -help' in the Tcl shell.
#
# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this
# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when
# executing this script. Please type 'axi_clock_converter_0.sh -help' for more information.
#
# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'
#
#*********************************************************************************************************

# Script info
echo -e "axi_clock_converter_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\n"

# Main steps
run()
{
  check_args $# $1
  setup $1 $2
  compile
  simulate
}

# RUN_STEP: <compile>
compile()
{
  # Compile design files
  source compile.do 2>&1 | tee -a compile.log

}

# RUN_STEP: <simulate>
simulate()
{
  vsim -64 -c -do "do {simulate.do}" -l simulate.log
}

# STEP: setup
setup()
{
  case $1 in
    "-lib_map_path" )
      if [[ ($2 == "") ]]; then
        echo -e "ERROR: Simulation library directory path not specified (type \"./axi_clock_converter_0.sh -help\" for more information)\n"
        exit 1
      fi
     copy_setup_file $2
    ;;
    "-reset_run" )
      reset_run
      echo -e "INFO: Simulation run files deleted.\n"
      exit 0
    ;;
    "-noclean_files" )
      # do not remove previous data
    ;;
    * )
     copy_setup_file $2
  esac

  create_lib_dir

  # Add any setup/initialization commands here:-

  # <user specific commands>

}

# Copy modelsim.ini file
copy_setup_file()
{
  file="modelsim.ini"
  lib_map_path="<SPECIFY_COMPILED_LIB_PATH>"
  if [[ ($1 != "" && -e $1) ]]; then
    lib_map_path="$1"
  else
    echo -e "ERROR: Compiled simulation library directory path not specified or does not exist (type "./top.sh -help" for more information)\n"
  fi
  if [[ ($lib_map_path != "") ]]; then
    src_file="$lib_map_path/$file"
    cp $src_file .
  fi
}

# Create design library directory
create_lib_dir()
{
  lib_dir="modelsim_lib"
  if [[ -e $lib_dir ]]; then
    rm -rf $lib_dir
  fi

  mkdir $lib_dir

}

# Delete generated data from the previous run
reset_run()
{
  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)
  for (( i=0; i<${#files_to_remove[*]}; i++ )); do
    file="${files_to_remove[i]}"
    if [[ -e $file ]]; then
      rm -rf $file
    fi
  done

  create_lib_dir
}

# Check command line arguments
check_args()
{
  if [[ ($1 == 1 ) && ($2 != "-lib_map_path" && $2 != "-noclean_files" && $2 != "-reset_run" && $2 != "-help" && $2 != "-h") ]]; then
    echo -e "ERROR: Unknown option specified '$2' (type \"./axi_clock_converter_0.sh -help\" for more information)\n"
    exit 1
  fi

  if [[ ($2 == "-help" || $2 == "-h") ]]; then
    usage
  fi
}

# Script usage
usage()
{
  msg="Usage: axi_clock_converter_0.sh [-help]\n\
Usage: axi_clock_converter_0.sh [-lib_map_path]\n\
Usage: axi_clock_converter_0.sh [-reset_run]\n\
Usage: axi_clock_converter_0.sh [-noclean_files]\n\n\
[-help] -- Print help information for this script\n\n\
[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\n\
using the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\n\n\
[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\n\
from the previous run will be removed. If you don't want to remove the simulator generated files, use the\n\
-noclean_files switch.\n\n\
[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\n\n"
  echo -e $msg
  exit 1
}

# Launch script
run $1 $2


#!/bin/bash -f
#*********************************************************************************************************
# Vivado (TM) v2020.2 (64-bit)
#
# Filename    : axi_clock_converter_0.sh
# Simulator   : Mentor Graphics Questa Advanced Simulator
# Description : Simulation script for compiling, elaborating and verifying the project source files.
#               The script will automatically create the design libraries sub-directories in the run
#               directory, add the library logical mappings in the simulator setup file, create default
#               'do/prj' file, execute compilation, elaboration and simulation steps.
#
# Generated by Vivado on Tue Dec 14 16:44:13 CST 2021
# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020
#
# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved.
#
# usage: axi_clock_converter_0.sh [-help]
# usage: axi_clock_converter_0.sh [-lib_map_path]
# usage: axi_clock_converter_0.sh [-noclean_files]
# usage: axi_clock_converter_0.sh [-reset_run]
#
# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the
# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the
# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch
# that points to these libraries and rerun export_simulation. For more information about this switch please
# type 'export_simulation -help' in the Tcl shell.
#
# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this
# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when
# executing this script. Please type 'axi_clock_converter_0.sh -help' for more information.
#
# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'
#
#*********************************************************************************************************

# Script info
echo -e "axi_clock_converter_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\n"

# Main steps
run()
{
  check_args $# $1
  setup $1 $2
  compile
  elaborate
  simulate
}

# RUN_STEP: <compile>
compile()
{
  # Compile design files
  source compile.do 2>&1 | tee -a compile.log

}

# RUN_STEP: <elaborate>
elaborate()
{
  source elaborate.do 2>&1 | tee -a elaborate.log
}

# RUN_STEP: <simulate>
simulate()
{
  vsim -64 -c -do "do {simulate.do}" -l simulate.log
}

# STEP: setup
setup()
{
  case $1 in
    "-lib_map_path" )
      if [[ ($2 == "") ]]; then
        echo -e "ERROR: Simulation library directory path not specified (type \"./axi_clock_converter_0.sh -help\" for more information)\n"
        exit 1
      fi
     copy_setup_file $2
    ;;
    "-reset_run" )
      reset_run
      echo -e "INFO: Simulation run files deleted.\n"
      exit 0
    ;;
    "-noclean_files" )
      # do not remove previous data
    ;;
    * )
     copy_setup_file $2
  esac

  create_lib_dir

  # Add any setup/initialization commands here:-

  # <user specific commands>

}

# Copy modelsim.ini file
copy_setup_file()
{
  file="modelsim.ini"
  lib_map_path="<SPECIFY_COMPILED_LIB_PATH>"
  if [[ ($1 != "" && -e $1) ]]; then
    lib_map_path="$1"
  else
    echo -e "ERROR: Compiled simulation library directory path not specified or does not exist (type "./top.sh -help" for more information)\n"
  fi
  if [[ ($lib_map_path != "") ]]; then
    src_file="$lib_map_path/$file"
    cp $src_file .
  fi
}

# Create design library directory
create_lib_dir()
{
  lib_dir="questa_lib"
  if [[ -e $lib_dir ]]; then
    rm -rf $lib_dir
  fi

  mkdir $lib_dir

}

# Delete generated data from the previous run
reset_run()
{
  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)
  for (( i=0; i<${#files_to_remove[*]}; i++ )); do
    file="${files_to_remove[i]}"
    if [[ -e $file ]]; then
      rm -rf $file
    fi
  done

  create_lib_dir
}

# Check command line arguments
check_args()
{
  if [[ ($1 == 1 ) && ($2 != "-lib_map_path" && $2 != "-noclean_files" && $2 != "-reset_run" && $2 != "-help" && $2 != "-h") ]]; then
    echo -e "ERROR: Unknown option specified '$2' (type \"./axi_clock_converter_0.sh -help\" for more information)\n"
    exit 1
  fi

  if [[ ($2 == "-help" || $2 == "-h") ]]; then
    usage
  fi
}

# Script usage
usage()
{
  msg="Usage: axi_clock_converter_0.sh [-help]\n\
Usage: axi_clock_converter_0.sh [-lib_map_path]\n\
Usage: axi_clock_converter_0.sh [-reset_run]\n\
Usage: axi_clock_converter_0.sh [-noclean_files]\n\n\
[-help] -- Print help information for this script\n\n\
[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\n\
using the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\n\n\
[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\n\
from the previous run will be removed. If you don't want to remove the simulator generated files, use the\n\
-noclean_files switch.\n\n\
[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\n\n"
  echo -e $msg
  exit 1
}

# Launch script
run $1 $2