## ============================================================================
## retroDE_ps2 post_flow.tcl — Ch168 deployment-parity
## ----------------------------------------------------------------------------
## Mirrors the retroDE_nes / retroDE_splash / retroDE_a2600 post-Assembler
## artifact flow so the produced fabric image is "plug-in shaped" for the
## on-board core loader (`retroDE_splash/software/core_loader.sh`).
##
## What this emits (under `output_files/`):
##
##   <rev>.sof                       <-- bare fabric SOF from quartus_asm
##   <rev>_hps.sof                   <-- SOF merged with u-boot SPL (best-effort)
##   <rev>.rbf / <rev>.core.rbf      <-- whichever quartus_pfg produces given
##                                       this design's HPS configuration
##   <rev>_hps.jic                   <-- HPS-first JIC for QSPI (best-effort)
##   retroDE_ps2.core.rbf            <-- stable deploy artifact (Codex Ch168 contract)
##
## Design context: as of Ch168 retroDE_ps2's top is still HPS-less (no qsys
## subsystem in the design). The HPS-merge and HPS-aware split-RBF calls
## therefore *can* fail, because quartus_pfg has no HPS region in the SOF
## to merge u-boot SPL into. Those calls are wrapped in `catch` blocks and
## report failures as warnings, NOT errors, so the build flow can't be
## gated by them. The plain-RBF emit succeeds regardless and is what
## actually gets renamed to `retroDE_ps2.core.rbf`.
##
## If a future chapter adds a qsys/HPS subsystem to ps2 the same script
## starts producing proper split RBFs and the JIC — no edits required.
## ============================================================================

set module_name [lindex $quartus(args) 0]
set rev_name    [lindex $quartus(args) 1]

if {$module_name != "quartus_asm" && $module_name != "compile"} {
    return
}

set sof_file     "output_files/${rev_name}.sof"
set hps_sof_file "output_files/${rev_name}_hps.sof"
set rbf_file     "output_files/${rev_name}.rbf"
set rbf_split    "output_files/${rev_name}"
set core_rbf     "output_files/${rev_name}.core.rbf"
set jic_file     "output_files/${rev_name}_hps.jic"
set deploy_rbf   "output_files/retroDE_ps2.core.rbf"

# Resolve the shared HPS SPL hex relative to this script's on-disk location.
# Layout:
#   $script_dir = .../retroDE_ps2/synth/de25_nano/top_psmct32_raster_demo
#   $hps_hex   = .../retroDE_splash/software/u-boot/spl/u-boot-spl-dtb.hex
set script_dir [file dirname [file normalize [info script]]]
set hps_hex    [file normalize \
    [file join $script_dir ".." ".." ".." ".." \
        "retroDE_splash" "software" "u-boot" "spl" "u-boot-spl-dtb.hex"]]

if {![file exists $sof_file]} {
    post_message -type warning "post_flow: SOF not found ($sof_file), nothing to do"
    return
}

set hps_hex_ok [file exists $hps_hex]
if {!$hps_hex_ok} {
    post_message -type warning "post_flow: HPS SPL hex not found ($hps_hex); HPS-merge and JIC will be skipped"
}

# ---------------------------------------------------------------------------
# 1) Plain configuration RBF (no HPS). This is the artifact ps2 currently
#    ships — until the design grows a qsys HPS subsystem this is what
#    quartus_pfg can actually produce. Failure here is fatal-warning only
#    so the Quartus flow still reports success.
# ---------------------------------------------------------------------------
post_message -type info "post_flow: emitting plain configuration RBF"
if {[catch {qexec "quartus_pfg -c $sof_file $rbf_file"} rbf_result]} {
    post_message -type warning "post_flow: plain-RBF emit failed (non-fatal): $rbf_result"
} else {
    post_message -type info "post_flow: created $rbf_file"
}

# ---------------------------------------------------------------------------
# 2) HPS-merged SOF (best-effort — fails on HPS-less designs).
# ---------------------------------------------------------------------------
if {$hps_hex_ok} {
    post_message -type info "post_flow: attempting HPS-merged SOF (best-effort)"
    if {[catch {qexec "quartus_pfg -c $sof_file $hps_sof_file -o hps_path=$hps_hex"} merge_result]} {
        post_message -type warning "post_flow: HPS-merged SOF failed (expected if design has no HPS region): $merge_result"
    } else {
        post_message -type info "post_flow: created $hps_sof_file"
    }
}

# ---------------------------------------------------------------------------
# 3) HPS-aware split RBF (best-effort). When the SOF contains an HPS
#    region quartus_pfg writes <rev>.core.rbf + <rev>.hps.rbf. When it
#    doesn't, this call fails harmlessly.
# ---------------------------------------------------------------------------
if {$hps_hex_ok} {
    post_message -type info "post_flow: attempting HPS-aware split RBF (best-effort)"
    if {[catch {qexec "quartus_pfg -c $sof_file ${rbf_split}.rbf -o hps_path=$hps_hex -o hps=on"} split_result]} {
        post_message -type warning "post_flow: HPS-aware split RBF failed (expected if design has no HPS region): $split_result"
    } else {
        post_message -type info "post_flow: created $core_rbf / ${rbf_split}.hps.rbf"
    }
}

# ---------------------------------------------------------------------------
# 4) JIC for QSPI flash (best-effort).
# ---------------------------------------------------------------------------
if {$hps_hex_ok} {
    post_message -type info "post_flow: attempting HPS-first JIC (best-effort)"
    set jic_cmd "quartus_pfg -c $sof_file $jic_file \
        -o device=MT25QU128 -o flash_loader=A5EB013BB23BE4SCS \
        -o mode=ASX4 -o hps_path=$hps_hex -o hps=on"
    if {[catch {qexec $jic_cmd} jic_result]} {
        post_message -type warning "post_flow: JIC generation failed (expected if design has no HPS region): $jic_result"
    } else {
        post_message -type info "post_flow: created $jic_file"
    }
}

# ---------------------------------------------------------------------------
# 5) Stable deploy artifact: copy the best RBF we produced to
#    `retroDE_ps2.core.rbf` so downstream tooling has a fixed name.
#    Preference: <rev>.core.rbf (HPS-aware split, only exists if step 3
#    succeeded), else <rev>.rbf (plain, from step 1).
# ---------------------------------------------------------------------------
if {[file exists $core_rbf]} {
    file copy -force -- $core_rbf $deploy_rbf
    post_message -type info "post_flow: deploy artifact = $deploy_rbf (from HPS-aware split)"
} elseif {[file exists $rbf_file]} {
    file copy -force -- $rbf_file $deploy_rbf
    post_message -type info "post_flow: deploy artifact = $deploy_rbf (from plain RBF)"
} else {
    post_message -type warning "post_flow: no RBF was produced; deploy artifact $deploy_rbf NOT updated"
}
