#! /bin/bash

#-----------------------------------------------------------------------------
# Title      : Do Vivado merge elf into bit using mmi
#-----------------------------------------------------------------------------
# File       : do_vivado_mmi_elf.sh
# Author     : Pascal Bos <bosp@nikhef.nl>
# Company    : Nikhef
# Created    : 2020-07-09
# Last update: 2022-04-13
# Platform   : FPGA-generics
# Standard   : VHDL
#-----------------------------------------------------------------------------
# Description:
#
# This script merge elf into bit using mmi
#-----------------------------------------------------------------------------
#
# Copyright (c) 2021 Nikhef, Peter Jansweijer
#
# This source file is free software; you can redistribute it   
# and/or modify it under the terms of the GNU Lesser General   
# Public License as published by the Free Software Foundation; 
# either version 2.1 of the License, or (at your option) any   
# later version.                                               
#
# This source is distributed in the hope that it will be       
# useful, but WITHOUT ANY WARRANTY; without even the implied   
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR      
# PURPOSE.  See the GNU Lesser General Public License for more 
# details.                                                     
#
# You should have received a copy of the GNU Lesser General    
# Public License along with this source; if not, download it   
# from http://www.gnu.org/licenses/lgpl-2.1.html
#
#-----------------------------------------------------------------------------

proj_name=$(basename $1 .bit)
wrpc_cpu_mmi=${proj_name}.mmi
wrpc_cpu_elf=$2
wrpc_cpu_instpath="wrpc_cpu_memory"

if not [ -f "$1" ]; then
    echo "$1 bit file not found"
    echo "Usage: do_vivado_mmi_elf.sh <bitfile>.bit <elffile>.elf"
    exit
fi
if not [ ${1: -4} == ".bit" ]; then
    echo "$1 bit file not found"
    echo "Usage: do_vivado_mmi_elf.sh <bitfile>.bit <elffile>.elf"
    exit
fi

if not [ -f "$2" ]; then
    echo "$1 elf file not found"
    echo "Usage: do_vivado_mmi_elf.sh <bitfile>.bit <elffile>.elf"
    exit
fi
if not [ ${2: -4} == ".elf" ]; then
    echo "$2 elf file not found"
    echo "Usage: do_vivado_mmi_elf.sh <bitfile>.bit <elffile>.elf"
    exit
fi

if not [ -f "$wrpc_cpu_mmi" ]; then
    echo "$1 mmi file not found, has it been generated?"
    exit
fi

# Cleanup old log files and stuff
rm vivado_mmi_elf.log 2>/dev/null
rm updatemem*.jou 2>/dev/null
rm updatemem*.log 2>/dev/null

updatemem -meminfo ${proj_name}.mmi -data $2 -bit $1 -proc $wrpc_cpu_instpath -out ${proj_name}_elf.bit -force >> vivado_mmi_elf.log
