#!/usr/bin/env python3

import os
import re
import requests

"""
Update index.html to localise shields.io images

Replace
<img src="https://img.shields.io/maven-central/v/org.apache.bcel/bcel"
with
<img src="_shields/org.apache.bcel_bcel.svg"
and download the file into _shields

"""
FILE = 'target/site/index.html'
TEMP = 'target/site/index.html.tmp'
# Note that the Maven groupId and artifactId fields are used to create a file,
# so only a restricted set of characters are allowed.
URL_RE = r'<img src="(https://img\.shields\.io/maven-central/v/([-a-z.]+/[-a-z0-9]+))"'

def main():
    with open(FILE, 'r', encoding='utf-8') as i, open(TEMP, 'w', encoding='utf-8') as o:
        for line in i:
            m = re.search(URL_RE, line)
            if m:
                src = m.group(1)
                res = requests.get(src)
                comp = m.group(2).replace('/', '_')
                out = f'_shields/{comp}.svg'
                with open('target/site/'+ out, 'wb') as wb:
                    wb.write(res.content)
                line = line.replace(src, out)
            o.write(line)
    os.rename(TEMP, FILE)
if __name__ == '__main__':
    main()