#
# Copyright 2020 Ettus Research, a National Instrument Brand
#

# This script generates the indicated IP, patches it, then builds it with the
# patch.

# ---------------------------------------
# Gather all external parameters
# ---------------------------------------
set xci_file         $::env(XCI_FILE)               ;# Absolute path to XCI file from src dir
set part_name        $::env(PART_NAME)              ;# Full Xilinx part name
set gen_example_proj $::env(GEN_EXAMPLE)            ;# Generate an example project
set synth_ip         $::env(SYNTH_IP)               ;# Synthesize generated IP
set ip_name [file rootname [file tail $xci_file]]   ;# Extract IP name
set patched_file     $::env(PATCHED_FILE)           ;# Path to patched version of the file
set file_to_patch    $::env(FILE_TO_PATCH)          ;# Path to file that needs to be patched

# Delete any previous output cookie file
file delete -force "$xci_file.out"

# ---------------------------------------
# Vivado Commands
# ---------------------------------------
create_project -part $part_name -in_memory -ip
set_property target_simulator XSim [current_project]
add_files -norecurse -force $xci_file
reset_target all [get_files $xci_file]
puts "BUILDER: Generating IP Target..."
generate_target all [get_files $xci_file]
puts "BUILDER: Patching IP..."
puts "Patched file is:"
puts "$patched_file"
puts "File to patch is:"
puts "$file_to_patch"
file copy -force "$patched_file" "$file_to_patch"
if [string match $synth_ip "1"] {
    puts "BUILDER: Synthesizing IP Target..."
    synth_ip [get_ips $ip_name]
}
if [string match $gen_example_proj "1"] {
    puts "BUILDER: Generating Example Design..."
    open_example_project -force -dir . [get_ips $ip_name]
}
close_project

if { [get_msg_config -count -severity ERROR] == 0 } {
    # Write output cookie file
    set outfile [open "$xci_file.out" w]
    puts $outfile "This file was auto-generated by viv_generate_ip.tcl and signifies that IP generation is done."
    close $outfile
} else {
    exit 1
}
