#!/usr/bin/python3
import glob
import json
import os
import re
import sys
import time
import urllib.request
import urllib.error

SYN = "http://127.0.0.1:8008"
DATA = "/var/lib/telodendria"
MEDIA = DATA + "/media"
OLD_HOST = "marlonivo.com"
NEW_HOST = "matrix2.marlonivo.com"
DRY = "--dry" in sys.argv


def fetch(media_id):
    url = SYN + "/_matrix/media/v3/download/" + OLD_HOST + "/" + media_id
    try:
        req = urllib.request.Request(url)
        with urllib.request.urlopen(req, timeout=15) as r:
            if r.status != 200:
                return None
            return r.read(), r.headers.get("Content-Type", "application/octet-stream")
    except Exception:
        return None


def main():
    files = glob.glob(DATA + "/rooms/*/state.json") + glob.glob(DATA + "/users/*.json")
    refs = {}
    for p in files:
        s = open(p).read()
        found = re.findall(r'mxc://([^/"\\]+)/([A-Za-z0-9_-]+)', s.replace('\\/', '/'))
        for h, i in found:
            if h == OLD_HOST:
                refs.setdefault(i, 0)
                refs[i] += 1

    copied = skipped = failed = 0
    for i, count in sorted(refs.items()):
        dest = MEDIA + "/" + i
        meta = dest + ".json"
        if os.path.exists(dest) and os.path.exists(meta):
            skipped += 1
            continue
        got = fetch(i)
        if not got:
            failed += 1
            print("FETCH-FAIL", i, flush=True)
            continue
        data, ctype = got
        if not DRY:
            with open(dest, "wb") as f:
                f.write(data)
            with open(meta, "w") as f:
                json.dump({
                    "upload_name": i,
                    "created": int(time.time()),
                    "size": len(data),
                    "content_type": ctype,
                }, f, separators=(",", ":"))
        copied += 1
        print("MEDIA", i, len(data), ctype, "refs", count, flush=True)

    rew = 0
    if not DRY:
        for p in files:
            s = open(p).read()
            new = s.replace("mxc://" + OLD_HOST + "/", "mxc://" + NEW_HOST + "/")
            new = new.replace("mxc:\\/\\/" + OLD_HOST + "\\/",
                              "mxc:\\/\\/" + NEW_HOST + "\\/")
            if new != s:
                open(p, "w").write(new)
                rew += 1
    print("SUMMARY media=%d skipped=%d failed=%d files_rewritten=%d dry=%s"
          % (copied, skipped, failed, rew, DRY), flush=True)


if __name__ == "__main__":
    main()
