#!/bin/sh
# simple script to check the progress

gawk -- '
BEGIN {
  index_count = 0
  index_delta = 0
  index_time = 0
  delete parse_count
  delete parse_delta
  delete parse_time
  delete parse_max
  delete render_count
  delete render_delta
  delete render_max
  quotes = "['"'"'\"]"
}

END {
    if (0 != index_delta) {
        printf("Index: %15d         %8.2fs per %5d\n", index_count, (index_time / (index_count / index_delta)), index_delta)
    } else {
        print "Index: Not Started"
    }

    if (0 != length(parse_delta)) {
        for (i in parse_delta) {
            if (0 == parse_max[i]) {
                if (i in render_max) {
                    complete = 100
                } else {
                    complete = 0
                }
            } else {
                complete = 100 * parse_count[i] / parse_max[i]
            }
            average = parse_time[i] / (parse_count[i] / parse_delta[i])
            printf("Parse[%2d]: %11d %6.1f%% %8.2fs per %5d\n", i, parse_count[i], complete, average, parse_delta[i])
        }
    } else {
        print "Parse: Not Started"
    }

    if (0 != length(render_delta)) {
        for (i in render_delta) {
            n = render_max[i]
            if (0 == n) {
                n =  parse_count[i]
            }
            if (0 != n) {
                complete = 100 * render_count[i] / n
            } else {
                complete = 0
            }
            average = render_time[i] / (render_count[i] / render_delta[i])
            printf("Render[%2d]: %10d %6.1f%% %8.2fs per %5d\n", i, render_count[i], complete, average, render_delta[i])
        }
    } else {
        print "Render: Not Started"
    }
}

/^Index:/ {
    index_time += $2
    n = $3
    index_delta = n - index_count
    index_count = n
}

/^make[[:space:]]+RENDER_BLOCK=.*parse/ {
    n = gensub("^[^=]*=" quotes "*([[:digit:]]+)" quotes "*.*$", "\\1", "", $2) + 0
    c = gensub("^[^=]*=" quotes "*([[:digit:]]+)" quotes "*.*$", "\\1", "", $4) + 0
    sub("k", "000", c)
    if ("all" == c) {
        c = 0
    }
    parse_max[n] = c
    render_max[n] = c
}

/^Parse\[/ {
    p1 = index($0, "-")
    p2 = index($0, ".")
    if (p1 > 0 && p2 > 0) {
        i = substr($0, p1 + 1, p2 - p1 - 1)
        if ("Total:" == $2) {
           parse_count[i] = $3
           parse_max[i] = $3
        } else {
            parse_time[i] += $2
            n = $3
            parse_delta[i] = n - parse_count[i]
            parse_count[i] = n
        }
    }
}

/^Render\[/ {
    p1 = index($0, "[")
    p2 = index($0, "]")
    if (p1 > 0 && p2 > 0) {
        i = substr($0, p1 + 1, p2 - p1 - 1)
        if ("Total:" == $2) {
           render_count[i] = $3
           render_max[i] = $3
        } else {
            render_time[i] += $2
            n = $3
            render_delta[i] = n - render_count[i]
            render_count[i] = n
        }
    }
}


' "$@"
