#
# ##############################################################################
#
# software project builder for BootLoading lab
#
# todo:
#    update to Vitis
#
# history
#    2022/02/01 - WK - 2021.2 - configured for only MPSoC use as Versal is suppored by the Versal Boot and Config lab
#    2022/01/21 - RS - 2021.2 - removing -quiet from the pseudo-environment variable
#    2021/11/04 - WK - 2021.2 - using pseudo-environment variable
#    2021/09/01 - WK - 2021.1 - env var update
#    2020/03/06 - WK - updated for Vitis in 2019.2
#    2019/12/03 - LR - updated to use sharedResources hardware and 2019.1
#    2018/01/09 - WK - cleaned up for 2018.1 release (and 2017.3 re-release)
#
# ##############################################################################
#
set badEnv 0;
if {[catch {variable trainingPath $::env(TRAINING_PATH)} emsg]} {
   puts "ERROR!!! TRAINING_PATH environment variable not defined!";
    set badEnv 1;
} else {
   regsub -all {\\} $trainingPath / trainingPath;
}

# load the pseudo-environment variables
source $trainingPath/CustEdLoader.tcl; custEdLoad;

puts "Version 2021.2 - 2022/01/21";

variable tools $trainingPath/tools;

if {$badEnv} {
   puts "cannot continue until environment variables properly set - exiting...";
   puts -nonewline "Hit Enter to continue ==> ";
   flush stdout;
   gets stdin;
}

# load the helper script (-quiet not supported in XSCT)
source $trainingPath/CustEdIP/helper.tcl

if {[info exists helper_loaded] != 1} {
   echo "Helper.tcl failed to load!";
   exit;
}

source $trainingPath/CustEdIP/vitis_helper.tcl;  

# set up description of projects
variable tcName        bootLoading;
variable labName       $tcName;
variable labOrDemo     lab;
variable platName      bootLoading_plat;
variable sysName       bootLoading_sys;
variable domName       bootLoading_dom;
variable appName       bootLoading_app;
variable appTemplate  {Empty Application(C)};
variable hwName        undefined;
variable hwSpec        undefined;
variable platform      zcu104;
variable processorName psu_cortexa53_0;

variable verbose      1;

# internal debug assist: source /Xilinx_SVN/trunk/Embedded/TopicClusters/bootLoading/bootLoading_builder.tcl;

# identify the steps in this lab following the _completer module. Note: there is not yet a "make" function 
set stepList {{boardSelect(ZCU104) buildStartingPoint}\
              {sourcesAdd(LED_Controller) modifyTemplates synthesisRun}
              {familiesAdd }
             }

# sets the variables used to direct the building of the projects
proc boardSelect {thing} {
   variable processorName;
   variable platform;
   variable debug;
   variable verbose;
   
   # figure out which board is being used and set the platform and processor names
   #if {[string equal -nocase $thing VCK190es]} {
   #   set platform vck190_es1;
   #   set processorName psv_cortexa72_0;
   #} elseif {[string equal -nocase $thing VCK190]} {
   #   set platform vck190;
   #   set processorName psv_cortexa72_0;
   #} else
   if {[string equal -nocase $thing ZCU104]} {
      set platform zcu104;
      set processorName psu_cortexa53_0;
   } else {
      puts stderr "unknown platform: $thing";
      return;
   }
}

# 1-2-4
proc buildStartingPoint {} {
   variable trainingPath;
   variable tcName;
   variable platName;
   variable hwSpec ;
   variable domName;
   variable sysName;
   variable appName;
   variable appTemplate;
   variable processorName;
   variable platform;
   variable labOrDemo;
   variable verbose;
   if {$verbose} { puts "bootLoading_builder.tcl:buildStartingPoint"; }
      
   # make sure we're in the right place
   set workspaceName [getws];
   set targetWorkspace $trainingPath/$tcName/lab;
 
   # if there is a drive specifier listed, make sure that it's capitalized
   if {[string first : $targetWorkspace] == 1 } { 
      set drive [string toupper [string range $targetWorkspace 0 1]];
      # replace drive with forced uppercase
      set strippedTargetWorkspace [string range $targetWorkspace 2 [string length $targetWorkspace]];
      set targetWorkspace $drive;
      append targetWorkspace $strippedTargetWorkspace;
   }

   # now look to see if we're in the right place
   puts "going to compare: $targetWorkspace with $workspaceName";
   if {$workspaceName != $targetWorkspace} {
      puts "The workspace should be $targetWorkspace, but instead we're in $workspaceName.";
      puts "This mismatch will cause the script to fail, so we're going to force the workspace to the right place and continue...";
      setws $targetWorkspace;
      if {[getws] != $targetWorkspace} {
         puts "Hey, I tried, but couldn't change the workspace. You must change the workspace to $targetWorkspace and re-run this script."
         puts "Exiting now...";
         exit 1;
      }
   } else {
      puts "Workspace $workspaceName verified! Continuing...";
   }
   
   # clear the workspace (removal of platform projects still doesn't work - skip this for now and try again in the next release)
   projRemove all;
   
   # ensure that the MPSoC is selected
   boardSelect ZCU104;
   
   # create a platform project from the XSA - if the project to build can't be found in the existing projects list, then ...	
   set    hwSpec $trainingPath/CustEdIP/UED_;
   append hwSpec $platform .xsa;
   puts "Creating the Platform Project $platName based on $hwSpec";
   set startTime [clock seconds];
   platform create -name $platName -hw $hwSpec -desc {Platform project for SystemDebugger lab};
   set elapsedTime [expr [clock seconds] - $startTime];
   puts "Platform created in $elapsedTime seconds";
    
   # next build the Domain for the newly created platform project
   set startTime [clock seconds];
   domain create -name $domName -proc $processorName -os standalone -desc {standalone BSP supporting first processor in the cluster};
   set elapsedTime [expr [clock seconds] - $startTime];
   puts "Domain created in $elapsedTime seconds";
   
   # customize the domain to include the xilinx fat file system 
   #set libList { { xilffs fs_interface 2 } { xilffs ramfs_size 2098152000 } }
   set libList {};
   domBuild $libList;

   # then build the application and load the provided files
   set labSourceList  { bootLoading_main.c utils_print.c utils_print.h platform.h platform_config.h};
   set demoSourceList { bootLoading_main.c utils_print.c utils_print.h platform.h platform_config.h};

   if {[string compare -nocase $labOrDemo lab] == 0} { set filesToCopy $labSourceList; } else { set filesToCopy $demoSourceList; }
   set startTime [clock seconds];
   appBuild $filesToCopy;
   set elapsedTime [expr [clock seconds] - $startTime];
   puts "Application project created in $elapsedTime seconds";

   # now that the projects are created, build everything related to this application
   set startTime [clock seconds];
   app build -name $appName;
   set elapsedTime [expr [clock seconds] - $startTime];
   
   puts "App and platform built in $elapsedTime seconds";
}

# done
puts "Done loading bootLoading_builder.tcl";

#<copyright-disclaimer-start>
#  ************************************************************************************************************
#  * © Copyright 2017-2022 Xilinx, Inc. All rights reserved.                                                  *
#  * This file contains confidential and proprietary information of Xilinx, Inc. and                          *
#  * is protected under U.S. and international copyright and other intellectual property laws.                *
#  * DISCLAIMER                                                                                               *
#  * This disclaimer is not a license and does not grant any rights to the materials distributed              *
#  * herewith. Except as otherwise provided in a valid license issued to you by Xilinx, and to the            *
#  * maximum extent permitted by applicable law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS"               *
#  * AND WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, EXPRESS,                 *
#  * IMPLIED, OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-INFRINGEMENT,     *
#  * OR FITNESS FOR ANY PARTICULAR PURPOSE; and (2) Xilinx shall not be liable (whether in contract or tort,  *
#  * including negligence, or under any other theory of liability) for any loss or damage of any kind or      *
#  * nature related to, arising under or in connection with these materials, including for any direct, or     *
#  * any indirect, special, incidental, or consequential loss or damage (including loss of data, profits,     *
#  * goodwill, or any type of loss or damage suffered as a result of any action brought by a third party)     *
#  * even if such damage or loss was reasonably foreseeable or Xilinx had been advised of the possibility     *
#  * of the same.                                                                                             *
#  * CRITICAL APPLICATIONS                                                                                    *
#  * Xilinx products are not designed or intended to be fail-safe, or for use in any application requiring    *
#  * fail-safe performance, such as life-support or safety devices or systems, Class III medical devices,     *
#  * nuclear facilities, applications related to the deployment of airbags, or any other applications that    *
#  * could lead to death, personal injury, or severe property or environmental damage (individually and       *
#  * collectively, "Critical Applications"). Customer assumes the sole risk and liability of any use of       *
#  * Xilinx products in Critical Applications, subject only to applicable laws and regulations governing      *
#  * limitations on product liability.                                                                        *
#  * THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS PART OF THIS FILE AT ALL TIMES.                 *
#  *                                                                                                          *
#  ************************************************************************************************************
#<copyright-disclaimer-end>
