#!/usr/bin/env bash
# Vitis HLS batch wrapper for FAT-driven builds.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
TCL_SCRIPT="${FAT_HLS_TCL_SCRIPT:-$SCRIPT_DIR/run_hls.tcl}"
VITIS_SETTINGS="${FAT_VITIS_SETTINGS:-$REPO_ROOT/tools/Vitis_HLS/2022.2/settings64.sh}"
EXPORT_ZIP="${FAT_HLS_EXPORT_ZIP:-$SCRIPT_DIR/export/export.zip}"
EXPORT_DIR="$(dirname "$EXPORT_ZIP")/export"

if [[ -f "$VITIS_SETTINGS" ]]; then
  echo "Sourcing Vitis environment: $VITIS_SETTINGS"
  # shellcheck disable=SC1090
  source "$VITIS_SETTINGS"
else
  echo "Error: Vitis settings file not found at: $VITIS_SETTINGS"
  exit 1
fi

if ! command -v vitis_hls >/dev/null 2>&1; then
  echo "Error: vitis_hls not in PATH after sourcing settings."
  exit 1
fi

if ! command -v unzip >/dev/null 2>&1; then
  echo "Error: unzip is not available in PATH."
  exit 1
fi

if [[ ! -f "$TCL_SCRIPT" ]]; then
  echo "Error: Tcl script '$TCL_SCRIPT' not found."
  exit 1
fi

echo "Running Vitis HLS with Tcl script: $TCL_SCRIPT"
cd "$SCRIPT_DIR"
vitis_hls -f "$TCL_SCRIPT"

if [[ ! -f "$EXPORT_ZIP" ]]; then
  echo "Error: expected HLS export archive was not produced at: $EXPORT_ZIP"
  exit 1
fi

echo "Extracting HLS export archive into: $EXPORT_DIR"
mkdir -p "$EXPORT_DIR"
unzip -o "$EXPORT_ZIP" -d "$EXPORT_DIR"

echo "All steps completed successfully."
