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

package require cmdline

# remaphist
#
# Make a standard emake history file relocatable (usable with a different but
# similar emake root) by replacing a path prefix with a variable reference;
# or make a relocatable history file usable by emake by expanding the variable
# reference and swizzling the resulting paths so they are relative to the new
# roots.
#
# Copyright (c) 2003-2026 Electric Cloud, Inc.
# All rights reserved.

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

set gMinHistoryVersion 4;       # Minimum history file version supported
set gMaxHistoryVersion 6;       # Maximum history file version supported

# ----------------------------------------------------------------------------
# Globals
# ----------------------------------------------------------------------------

set gNoRemap 0;                 # Counter of skipped remappable lines
set gHistoryVersion 0;          # History version read from header

#-----------------------------------------------------------------------------
# normalize
#
#       Perform platform specific path normalization.
#-----------------------------------------------------------------------------

if {$tcl_platform(platform) == "windows"} {
    # On Windows, convert the path to lowercase and replace backslashes with
    # forward slashes.

    proc normalize {file} {
        return [string map [list \\ /] [string tolower $file]]
    }
} else {
    # On non-Windows, nothing needs to be done.

    proc normalize {file} {
        return $file
    }
}

#-----------------------------------------------------------------------------
# pathTrim
#
#       If the prefix matches the path, trim off the prefix and store the
#       resulting path in the variable specified by varName.  Returns true
#       if the prefix matched, otherwise returns false.
#-----------------------------------------------------------------------------

proc pathTrim {path prefix varName} {
    upvar 1 $varName outPath
    set lpath [file split $path]
    set lprefix [file split $prefix]
    set lprefixlen [llength $lprefix]
    if {[llength $lpath] < [llength $lprefix]} {
        return false
    }
    foreach a $lprefix b [lrange $lpath 0 [expr {$lprefixlen - 1}]] {
        if {![string equal $a $b]} {
            return false
        }
    }

    # Strip the prefix from the path.  At this point we have:
    #
    #   lpath   => / foo bar baz
    #   lprefix => / foo
    #
    # So the straightfoward way to get the stripped path is to just [file join]
    # the elements in lpath that start after the length of lprefix.
    # Unfortunately, this has the side-effect of collapsing duplicate path
    # separators in path, so if $path actually has "/foo/bar//baz", we will
    # come back with "bar/baz", instead of "bar//baz".  Although the two paths
    # are semantically equivalent, they will not pass string equality tests,
    # which can ultimately result in conflicts in future emake runs (see
    # EC-3404). Therefore, we use the following algorithm instead:
    #
    #   1.  Use [string split] to split $path on / characters.  For our example
    #       path, that would give us "{} foo bar {} baz".
    #   2.  Walk through the resulting list, counting the non-empty elements
    #       and keeping track of the corresponding character index within the
    #       string of the path elements we've seen.
    #   3.  When we've seen as non-empty elements in the list as there are
    #       entries in lprefix, stop -- we now have the string index of the
    #       beginning of the path sans prefix.

    set lpath [split $path /\\]
    if { [lindex $lpath 0] == "" } {
        # A little special handling here for Unix paths, which start with /:
        # in the initial position, / is not a path separator per se, but a
        # path component itself.  If we treat it like a normal path separator
        # our counting gets messed up.

        set index 1
        set count 1
        set lpath [lrange $lpath 1 end]
    } else {
        set index 0
        set count 0
    }
    foreach el $lpath {
        incr index
        set len [string length $el]
        if { $len > 0 } {
            incr count
            incr index $len
            if { $count == $lprefixlen } {
                break
            }
        }
    }

    # Now that we know how much of the string the prefix represents, we know
    # what part of the string to return as the stripped path.

    set outPath [string range $path $index end]

    return true
}

#-----------------------------------------------------------------------------
# addVars
#
#       Check the current line for matches against the substitution variables.
#       If a path prefix matches the value of a variable, replace the match
#       with a variable reference and update the rootId to be -1.  Returns the
#       resulting line.
#
# Side effects:
#       Increments the gNoRemap counter if a root-relative path is not
#       remapped. 
#-----------------------------------------------------------------------------

proc addVars {roots vars line} {
    if {[regexp {^((?:\d+\s+\d+\s+)?)(\d+)\s*(.*)$} $line -> pre rootId path]
        && $rootId != 0} {
        if {$rootId > [llength $roots]} {
            error "Root id out of range: $rootId\n$line"
        } else {
            incr rootId -1
        }
        set newpath [normalize [lindex $roots $rootId]/$path]

        foreach {var val} $vars {
            if {[pathTrim $newpath $val newpath]} {
                set rootId -1
                set line "${pre}-1 \${$var}"
                if { [string length $newpath] } {
                    append line "/$newpath"
                }
                break
            }
        }
        if {$rootId != -1} {
            incr ::gNoRemap
        }
    }
    return $line
}

#-----------------------------------------------------------------------------
# expandVars
#
#       Expand a variable reference at the beginning of a path if the rootId
#       is -1.  Trims the expanded path to one of the new roots if possible.
#       Returns the updated line.
#-----------------------------------------------------------------------------

proc expandVars {roots vars line} {
    if {[regexp {^((?:\d+\s+)*)-1\s*(.*)$} $line -> pre path]} {
        set l [file split $path]
        set head [lindex $l 0]

        foreach {var val} $vars {
            if {$head == "\${$var}"} {
                # Replace the head of the path with the variable value
                set len  [string length $head]
                set path [string replace $path 0 [expr {$len - 1}] $val]

                # Now trim the path to one of the roots, if possible

                set index 1
                set rootId 0
                foreach root $roots {
                    if {[pathTrim $path $root path]} {
                        set rootId $index
                        break
                    }
                    incr index
                }

                set line "${pre}$rootId"
                if { [string length $path] > 0 } {
                    append line " $path"
                }
                return $line
            }
        }

        error "Unable to expand line:\n$line"
    }
    return $line
}

#-----------------------------------------------------------------------------
# makeRelocatable
#
#       Remap a file from a user context into a canonical form.  Reads the
#       specified file stream and stores the remapped data in global variables.
#-----------------------------------------------------------------------------

proc makeRelocatable {contents roots vars mappedVar} {
    upvar 1 $mappedVar newContents

    # Parse the ROOTS list out of the comment block.

    set gotRoot 0
    set oldRoots {}
    set i 0
    foreach line $contents {
        if {[string index $line 0] != "\#" && [string trim $line] != ""} {
            break
        } else {
            if {[string match *ROOTS:* $line]} {
                set gotRoot 1
            } elseif {$gotRoot} {
                set root [string trim [string range $line 1 end]]
                if {$root != ""} {
                    lappend oldRoots [normalize $root]
                }
            }
        }
        incr i
    }

    set contents [lrange $contents $i end]

    set warning {}

    # Determine the value to use for the root list.  Use the list from the
    # environment or command line if present, otherwise use the original
    # values from the history file.  If neither is present, generate an error.
    # Warn if both are present and they don't match.

    if {[llength $oldRoots] == 0} {
        error "Could not determine emake roots used to generate history file"
    } elseif {[llength $roots] == 0} {
        set roots $oldRoots
    } elseif {[llength $oldRoots] != 0 && $oldRoots != $roots} {
        append warning "Warning: current roots do not match roots used to generate history file,\n"
        append warning "ignoring root values in file"
    }

    # Generate new header block


    set newContents [parseContent $contents $roots $vars addVars]

    if {$::gNoRemap > 0} {
        append warning "warning: $::gNoRemap path[expr {($::gNoRemap > 1 ? {s} : {} )}] inside the emake root not remapped"
    }

    if { $warning != "" } {
        error $warning {} WARNING
    }
    return
}

#-----------------------------------------------------------------------------
# makeRelocatableHeader
#
#       Generate a header for a relocatable history file.
#-----------------------------------------------------------------------------

proc makeRelocatableHeader {version roots} {
    set template {EMAKEDATA %d VAR

# This file is a relocatable emake history file.  It must be remapped to
# the current user context before use.  Do not edit the contents by hand.
}
    return [format $template $version]
}

#-----------------------------------------------------------------------------
# makeFixed
#
#       Remap a relocatable history file into a specific user context.
#       Replaces variable references with the current values from the 
#       environment.  Generates a new header block that includes the current
#       list of roots.
#-----------------------------------------------------------------------------

proc makeFixed {contents roots vars newContentsVar} {
    upvar 1 $newContentsVar newContents

    # Skip header block

    set i 0
    foreach line $contents {
        if {[string index $line 0] != "\#" && [string trim $line] != ""} {
            break
        }
        incr i
    }
    
    set contents [lrange $contents $i end]

    # Generate new header block including the updated root list

    set newContents [parseContent $contents $roots $vars expandVars]
}

#-----------------------------------------------------------------------------
# makeFixedHeader
#
#       Generate a history file header for a history file with a specific
#       user context.
#-----------------------------------------------------------------------------0

proc makeFixedHeader {version roots} {
    set template {EMAKEDATA %d

# This file is generated automatically by Electric Make.
# Do not edit the contents by hand.
#
# ROOTS:
}
    set header [format $template $version]
    foreach root $roots {
        append header "#   $root\n"
    }
    return $header
}

#-----------------------------------------------------------------------------
# parseContent
#
#       Process the body of a history file, transforming each line
#       through the specified function.
#
# Arguments
#       contents  - (list) list of lines to process
#       roots     - (list) list of roots
#       func      - (proc) name of function to call on each line
#-----------------------------------------------------------------------------

proc parseContent {contents roots vars func} {
    
    # Five sections, with whitespace between them.
    # 'currSection' index incremented through section list.

    set sections {0 make 0 jobs 0 serialdeps 0 prereqs 0 prereqdeps}
    set section [lindex $sections [set currSection 0]]

    # Process contents line-by-line.

    set result {}
    foreach line $contents {
        
        # Blank/nonblank line boundaries advance to next section.
        
        if {($line == "" && $section != "0") ||
            ($line != "" && $section == "0")} {
            set section [lindex $sections [incr currSection]]
        }

        # Remap if we're in a section that needs it.

        if {$section == "make" || $section == "jobs" || $section == "prereqs"} {
            set line [$func $roots $vars [string trim $line]]
        }
        lappend result $line
    }
    return $result
}

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

proc main {} {
    global argv

    set options \
        [list \
             {u          "unmap history file - prepare for use in a new location"} \
             {s.arg      1  "sort roots \[01]"} \
             {i.arg      "" "input history file name"} \
             {o.arg      "" "output history file name"} \
             [list r.arg "" "emake root(s)"] \
            ]

    set usage "\n\n\
    Helps to make a history file usable in differing build environments. It\n\
    converts the bases of paths in a history file to variables. Later in some \n\
    other location or machine the variables can be expanded to new values \n\
    which match the new environment. \n\ e.g. '/home/user/fred.txt' becomes \n\
    '\${HOME}/fred.txt' by remapping and then \n\ may be unmapped to \n\
    '/build/docs/fred.txt'. \n\n\
    The -r option allows one to perform remapping and unmapping with the assumption \n\
    of specific emakeroots such that the paths in the input (remapping) and \n\
    output (unmapping) file are relative to those roots. \n\n\
    The -s options allows one to specify whether or not the root directories \n\
    should be sorted. The default is 1 which is sorted.\n\n\
    Usage when remapping a file to make it relocatable: \n\
    \tremaphist -i <input_file> -o <output_file>  \[-r <emake_roots>\] /an/absolute/path=MYVAR \[/another/path=MYOTHERVAR\] ... \n\n\
    Usage when converting it back (unmapping): \n\
    \tremaphist -u -i <input_file> -o <output_file>  \[-r <emake_roots>\] MYVAR=/a/new/abs/path \[MYOTHERVAR=/another/diff/path\] ... \n\noptions:"
    if {[catch {array set params \
                    [cmdline::getoptions argv $options $usage]} msg]} {
        if {[llength $argv]} {
            puts stderr "unknown option: $argv\n\n$msg"
            exit 1
        } else {
            puts $msg
            exit 0
        }
    }

    # Compute current variable values

    set vars {}
    foreach assignment $argv {
        set var $assignment
        set variableAssignment [split $assignment {=}]
        if {[llength $variableAssignment] == 2} {
            # there is an equals sign so use the lhs and rhs
            # /my/path=VAR  for mapping
            # VAR=/other/path for unmapping
            if {$params(u) == 1} {
                set var  [lindex $variableAssignment 0]
                set path [lindex $variableAssignment 1]
            } else {
                set var  [lindex $variableAssignment 1]
                set path [lindex $variableAssignment 0]
            }
            lappend params(impliedRoots) $path
        } else {
            # without an equals, assume it's the name of a variable to
            # pull from the environment. Mimics older behaviour. Probably worth
            # removing.
            if {![info exists ::env($var)]} {
                puts stderr "Assumed $var was referencing a variable in the\
                        environment but can't find it there."
                exit 1
            } 
            set path $::env($var)
        }

        if {[file pathtype $path] != "absolute"} {
            puts stderr "Mapping variable $var has a value ($path) which is not an absolute path."
            if {[string first [file separator] $var] != -1 && [string first [file separator] $path] == -1} {
                puts stderr "Did you mean $var=$path?"
            }
            exit 1
        }
        lappend vars $var [normalize $path]
    }

    if {[llength $vars] == 0} {
        # There is no reason to call this script without remapping
        # arguments and if someone didn't then they probably made and error
        puts stderr "remapping arguments are required. e.g. MYVAR=/some/absolute/path"
        exit 1
    }

    # Compute new root list

    if {$::tcl_platform(platform) == "windows"} {
        set pathSep ";"
    } else {
        set pathSep ":"
    }

    # Try to figure out the set of emake roots specified by the user:
    #
    #    If remaphist was invoked in "new" mode, where everything is given
    #    on the command-line, then the user should have specified "-r" to
    #    give the roots.  If the roots are *different* from the original,
    #    then this is required.  If "-r" was not specified in this mode,
    #    remaphist will guess the roots from the VAR=path mappings.
    #
    #    If remaphist was invoked in "old" mode where some information is
    #    pulled from the environment, then the user *may* have specified "-r"
    #    on the command-line, in which case we will honor that setting.  If
    #    "-r" was not specified on the command-line, remaphist will use
    #    the value of $env(EMAKE_ROOT), if present.

    if { [info exists params(impliedRoots)] } {
        if { [string length $params(r)] == 0 } {
            set params(r) [join $params(impliedRoots) $pathSep]
        }
    } else {
        if { [string length $params(r)] == 0 } {
            if {[info exists ::env(EMAKE_ROOT)]} {
                set params(r) $::env(EMAKE_ROOT)
            }
        }
    }

    set roots {}
    foreach root [split $params(r) $pathSep] {
        lappend roots [normalize $root]
    }

    if {$params(s) == 1 || $params(s) == "yes" || $params(s) == "true"} {
        set roots [lsort $roots]
    }

    # Open input file, bail if we can't.

    set inFile $params(i)
    if {$inFile == "" || $inFile == "-"} {
        set f stdin
    } elseif {[catch {open $inFile r} f]} {
        puts stderr "$f"
        exit 1
    }
    fconfigure $f -buffering full -buffersize 1000000

    if {([gets $f line] == -1)
        || (![regexp {^EMAKEDATA (\d+)( VAR)?} $line -> version type])} {
        puts stderr "Error reading history file, bad header: $line"
        exit 1
    }

    if {$version < $::gMinHistoryVersion || $version > $::gMaxHistoryVersion} {
        puts stderr "Version $version not supported"
        exit 1
    }
    set ::gHistoryVersion $version

    # Read the remaining contents and close the input file.

    set contents [split [read -nonewline $f] \n]
    catch {close $f}

    # Check the header type to determine the direction of remapping.

    if {$params(u) == 1} {
        if {$type != " VAR"} {
            puts stderr "Input file is not relocatable. Only relocatable files can be unmapped."
            exit 1
        }
        set generateHeader  makeFixedHeader
        set generateContent makeFixed
    } else {
        if {$type == " VAR"} {
            puts stderr "Input file is relocatable already - can't remap it ."
            exit 1
        }
        set generateHeader  makeRelocatableHeader
        set generateContent makeRelocatable
    }

    if { [catch {$generateContent $contents $roots $vars newContents} err] } {
        puts stderr $err
        if { $::errorCode != "WARNING" } {
            exit 1
        }
    }

    set header [$generateHeader $::gHistoryVersion $roots]

    # Now open the output stream and write the result.

    set outFile $params(o)
    if {$outFile == "" || $outFile == "-"} {
        set f stdout
    } elseif {[catch {open $outFile w} f]} {
        puts stderr "$f"
        exit 1
    }
    fconfigure $f -buffering full -buffersize 1000000

    puts $f $header
    if {[llength $newContents] > 0} {
        puts $f [join $newContents \n]
    }
    catch {close $f}
}

# Only run main if we're not being sourced by some
# other script:
if {[string last {remaphist} $::argv0] == [expr [string length $::argv0] - 9]} {
    main
}
