#!/bin/sh
# restart -*-Tcl-*- \
exec tclsh $0 "$@"

# eccc
#
# Electric Cloud CC wrapper.
#
# This script is a front-end to the Forte (aka Sun Workshop, aka
# SunOne Studio) CC compiler. It attempts to minimize the
# emake-unfriendly behavior of CC template repositories by letting
# individual compiles use their own repositories and then merging
# these custom repositories before link and archive operations.
#
# Copyright (c) 2003-2026 Electric Cloud, Inc.
# All rights reserved.

# ----------------------------------------------------------------------------
# Constants
# ----------------------------------------------------------------------------

set kCacheVar   SUNWS_CACHE_NAME;       # env var to specifiy repository name
set kCache      SunWS_cache;            # default repository name
set kState      CC_state;               # repository state file
set kECCache    eccache_;               # prefix for EC custom repositories

set kCC         /opt/SUNWspro/bin/CC;   # real path to Sun C++ compiler
if { [info exists env(ECCC_SUNCC)] } {
    # Sun CC is installed somewhere other than the default location, make sure
    # to use that path instead of the default.

    set kCC     $env(ECCC_SUNCC)
}

# ----------------------------------------------------------------------------
# main
# ----------------------------------------------------------------------------

proc main {} {
    eval {global env argv} [info vars ::k*]

    # Parse command line options. We're trying to determine whether
    # CC has been asked to do a link, a compile, an archive, or something
    # else. 

    # We are also trying to determine the directory that the objects
    # live in (objDir) and the directory that the target library/executable
    # is built in (outputDir).

    # We assume that it's NO-OP; ie, the wrapper falls straight through.

    set state NO-OP

    # Iterate over all options.

    for {set i 0} {$i < [llength $argv]} {incr i} {
        switch -glob -- [lindex $argv $i] {
            -o { 

                # '-o' could be any mode; if it was not already
                # set to ARCHIVE or COMPILE, set to LINK.

                if {$state == "NO-OP"} {
                    set state LINK
                }

                # It is immediately followed by the name of the output
                # file.  In archive and link mode, this is the output
                # directory; it is unused by compile mode.

                set outputDir [file dir [lindex $argv [incr i]]]
            }
            -xar {

                # '-xar' is positive for archive mode. We count on a '-o' to
                # tell us the name of the output directory.

                set state ARCHIVE
            }
            -c {
                
                # '-c' is positive for compile mode. We don't care
                # about output and object directories - we are just going
                # to use a custom repository.

                set state COMPILE
            }
            *.o {

                # A .o on the command line without a preceding '-o'
                # (caught above) is the input for a compile or link.
                # It lives in the object directory, where the template
                # repositories are created.

                set dir [file dir [lindex $argv $i]]
                set objDirs($dir) 1
            }
            default {
                # Ignore any other switches or arguments.
            }
        }
    }

    # Do we need to merge repositories?

    if {$state == "ARCHIVE" || $state == "LINK"} {
        
        # Yes. Save current dir before proceeding.

        set cwd [pwd]

        # Iterate over all the directories containing object files.

        foreach objDir [array names objDirs] {

            cd $objDir

            # Create the pathname of the canonical repository.
            # We won't actually create it until we know we need it.
            
            set cachePath [file join [pwd] $kCache]
            set cacheCreated 0

            # Iterate over all custom repositories.

            foreach rep [glob -nocomplain $kECCache*] {

                # Does this repository have a state file? (Some compiler
                # invocations will create an empty repository.)

                if [file exists $rep/$kState] {

                    # Yes. Enter the custom repository.

                    cd $rep

                    # Open the state file, and replace all references
                    # to the custom repository (eccache_*) with the name
                    # of the canonical repository (SunWS_cache).
                    
                    set f [open $kState r]
                    regsub -all "$kECCache\[^/\]*" [read $f] $kCache contents
                    close $f

                    # Append the contents to the canonical state file.

                    if {! $cacheCreated} {
                        file mkdir $cachePath
                    }

                    set f [open ../$kCache/$kState a]
                    puts -nonewline $f $contents
                    close $f

                    # Done with custom rep state file - remove it so it
                    # doesn't get copied by loop below.

                    file delete $kState

                    # Iterate over all remaining files and directories
                    # in the custom repository.

                    foreach f [glob *] {
                        
                        # Is this a file or a directory?

                        if {[file isdirectory $f]} {

                            # Directory. If the canonical repository
                            # doesn't have it, create it.

                            if {! [file exists ../$kCache/$f]} {
                                file mkdir ../$kCache/$f
                            }

                            # Look inside the dir, and copy all files
                            # to the canonical repository.
                            
                            foreach g [glob $f/*] {
                                file rename -force $g ../$kCache/$f
                            }

                        } else {

                            # File (usually '@_WARNING' or
                            # 'CC_version') - copy into the canonical
                            # repository.
                            
                            file rename -force $f ../$kCache 
                        }
                    }

                    # Leave the custom repository.

                    cd ..
                }

                # Delete the custom repository.

                file delete -force $rep
            }

            # Return to original directory after merging.

            cd $cwd
        }

    } elseif {$state == "COMPILE"} {

        # If we're compiling, set the cache environment
        # variable so that this run gets its own repository.

        # TODO - for incrementals, this should probably check to
        # see if a canonical rep exists, and if so, merge the
        # contents in, first.

        set env($kCacheVar) $kECCache[info hostname]_[clock seconds]_[agentID]
    }

    # Invoke the compiler as originally called.

    catch {eval exec $kCC $argv >@stdout 2>@stderr}

    # If we just built an archive, delete the cache created in the
    # output directory. We believe it isn't needed, and is just a
    # source of conflicts.

    # TODO - this will only work if EFS doesn't report usage on 
    # a directory that was created and removed in a job step: see
    # bug 630.

    #     if {$state == "ARCHIVE"} { 
    #         file delete -force $outputDir/$kCache
    #     }
}

# ----------------------------------------------------------------------------
# agentID
#
#       Extract the ID of the agent from the ECLOUD_RECURSIVE_COMMAND_FILE
#       environment variable.  If that variable is not defined, return "LOCAL",
#       otherwise return the ID.  This is used to guarantee that we don't get
#       name collisions between multiple simultaneous eccc instances on a 
#       single physical host when choosing temporary directory names.
# ----------------------------------------------------------------------------

proc agentID {} {
    global env

    set result LOCAL
    if { [info exists env(ECLOUD_RECURSIVE_COMMAND_FILE)] } {
        # The ECLOUD_RECURSIVE_COMMAND_FILE happens to encode the ID of the
        # agent running the process.  The format of the filename is:
        #
        #       ecagent#ID#PPPPP#NNNNNN
        #
        # where
        #
        #       ecagent is the literal string "ecagent"
        #       ID      is the agent ID.
        #       PPPPP   is the agent process ID.
        #       NNNNNN  is derived from the agent process start time.
        #
        # Split the word on the "#" characters and you should be able to pick
        # out the agent ID.  If it's not there, we'll stick with "LOCAL" as 
        # the name.

        set bits [split $env(ECLOUD_RECURSIVE_COMMAND_FILE) \#]
        foreach {prefix id pid time} $bits {
            break
        }

        if { ![string equal $id ""] } {
            set result $id
        }
    }
    return $result
}

if {[catch main result]} {
    set signature [info hostname]_[clock seconds]_[agentID]
    puts stderr "ERROR: Electric Cloud failure running CC on $signature"
    set f [open /tmp/eccc_$signature.err w]
    puts $f "Wrapper invoked as: $argv"
    puts $f "-------"
    puts $f $result
    puts $f "-------"
    puts $f $errorInfo
    close $f
}
