#!/bin/sh
##
## tcl procedures to generate a makefile compatible depend hierarchy for bluespec code

## \
exec bluetcl "$0" "$@"

#
namespace eval ::Depend {
    proc usage {} {
        set name [file tail $::argv0]
        puts stderr "usage: $name \[flag-arguments\] <glob pattern>"
        puts stderr "where flag-arguments are any valid bsc flags"
        puts stderr "Examples"
        puts stderr "  $name -p src2:+  -o dependency.file  Root.bsv"
        puts stderr "  $name -bdir objs  \"Root*.bsv\""
        puts stderr "  $name -no-show-timestamps Top.bsv"
        puts stderr "  $name -D MYDEF=yes Top.bsv"
    }


    proc isNotBSDIR { f } {
        if {[regexp BLUESPECDIR $f]} {
                return false
            }
            return true
    }
    proc cleanupdepend { line } {
        set f [lindex $line 0]
        set ds [lindex $line 1]
        set ds2 [list]
        foreach d $ds {
            if { [Depend::isNotBSDIR $d] } {
                regsub  {^./} $d "" d2
                lappend ds2 $d2
            }
        }
        regsub  {^./} $f "" f
        return "${f}:\t${ds2}"
    }
}


set argc [llength $argv]
if { $argc == 0 } {
    Depend::usage
    exit 1
}
set pattern [lindex $argv [expr $argc -1]]
if { [catch "glob $pattern" rootfiles] } {
    set rootfiles ""
}
if { $rootfiles == "" } {
    puts stderr "Error: $pattern did not match any files, exiting"
    exit 1
}

# scan options looking for command line options that we should consume
# (instead of passing to BlueTcl).
utils::scanOptions [list -no-show-timestamps] [list -o] 0 OPT $argv
set outfile stdout
if { [info exists OPT(-o)] } {
    if { [catch "open $OPT(-o) w" err] } {
        puts stderr $err
        exit 1
    } else {
        set outfile $err
    }
}

set flags [lrange $argv 0 [expr $argc -2]]

if { $flags != "" } {
    if { [catch "Bluetcl::flags set $flags" err] } {
        puts stderr $err
        exit 1
    }
}


set all [list]
foreach root $rootfiles {
    if { [catch "Bluetcl::depend make $root" tree] } {
        puts stderr "$tree"
        exit 1
    }
    set md [utils::map Depend::cleanupdepend $tree]
    set all [concat $all $md]
}

utils::listToSet D $all

set name [file tail $::argv0]
puts $outfile "## Automatically generated by $name -- Do NOT EDIT"
if {! [info exists OPT(-no-show-timestamps)] } {
    puts $outfile "## Date: [exec date]"
}
puts $outfile "## Command: $name $argv\n"
puts $outfile [join [lsort [utils::setToList D]] "\n"]
exit 0
