# Rewrites absolute-rooted href="/..." and src="/..." paths in a built Astro
# page into paths relative to that page's own location, so the site can be
# opened directly via file:// with no web server involved.
#
# Usage: awk -v prefix="../../" -f offline-rewrite.awk page.html > out.html
#
# Astro's directory-style routing means a link like href="/tools/nmap" is
# really a request for the file tools/nmap/index.html — an HTTP server
# resolves that automatically, file:// does not — so any path segment
# without a file extension gets /index.html appended. Protocol-relative
# ("//host/...") and same-page ("#anchor") references are left untouched.

function rewrite(u,    hash, q, i, path, n, segs, last) {
  hash = ""
  i = index(u, "#")
  if (i > 0) { hash = substr(u, i); u = substr(u, 1, i - 1) }

  q = ""
  i = index(u, "?")
  if (i > 0) { q = substr(u, i); u = substr(u, 1, i - 1) }

  path = substr(u, 2)  # drop the leading "/"
  if (path == "") {
    path = "index.html"
  } else {
    n = split(path, segs, "/")
    last = segs[n]
    if (index(last, ".") == 0) path = path "/index.html"
  }
  return prefix path q hash
}

{
  line = $0
  out = ""
  while (match(line, /(href|src)="\/[^"]*"/)) {
    pre = substr(line, 1, RSTART - 1)
    m = substr(line, RSTART, RLENGTH)
    eq = index(m, "=")
    attr = substr(m, 1, eq)
    url = substr(m, eq + 2, length(m) - eq - 2)

    if (substr(url, 2, 1) == "/") {
      newurl = url  # protocol-relative — leave alone
    } else {
      newurl = rewrite(url)
    }

    out = out pre attr "\"" newurl "\""
    line = substr(line, RSTART + RLENGTH)
  }
  print out line
}
