#! /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: 2021-06-01
# 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)
lm32_wrpc_mmi=${proj_name}.mmi
lm32_wrpc_elf=$2
lm32_wrpc_instpath="lm32_wrpc_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 "$lm32_wrpc_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 $lm32_wrpc_instpath -out ${proj_name}_elf.bit -force >> vivado_mmi_elf.log
