#!/usr/bin/python3

import os
import sys
import urllib.parse


def rel(f: str, dryrun: bool = False) -> None:
    d = os.path.abspath(os.path.realpath(os.path.dirname(f)))
    modded = False
    with open(f, "r") as obj:
        lines = obj.readlines()
    for n, line in enumerate(lines):
        linenonl = line.rstrip()
        if not line.strip():
            continue
        if line.startswith("#"):
            continue
        if urllib.parse.urlparse(linenonl).scheme:
            continue
        ffff = os.path.abspath(os.path.realpath(os.path.join(d, linenonl)))
        reld = os.path.normpath(os.path.relpath(ffff, d))
        if reld != linenonl:
            if dryrun:
                print(f"{f}:{n}: {linenonl} -> {reld}")
            line = reld + line[len(linenonl) :]
            lines[n] = line
            modded = True
    if modded and not dryrun:
        text = "".join(lines)
        b = os.path.basename(f)
        newf = os.path.join(d, ".tmp-" + b)
        with open(newf, "w") as obj:
            try:
                obj.write(text)
            except Exception:
                os.unlink(newf)
                raise
        try:
            os.rename(newf, f)
        except Exception:
            os.unlink(newf)


args = sys.argv[1:]
dryrun = False
while "-n" in args:
    dryrun = True
    args.remove("-n")
for f in args:
    try:
        rel(f, dryrun)
    except Exception as exc:
        print(f"error while relativizing {f}: {exc}", file=sys.stderr)
