#!/usr/bin/env python3
# preview-site.py <site> <docroot>
# Publica um preview em temp.prowel.com.br/<site>/ REWRITANDO caminhos absolutos
# (/css/..., /img/..., /js/..., /api/...) para /<site>/..., corrigindo os "links locais"
# do Open Studio (que usa caminhos absolutos e quebram em subpath).
import os, re, shutil, sys

site = sys.argv[1]
src = sys.argv[2]
dest = '/sites/temp/' + site

shutil.rmtree(dest, ignore_errors=True)
shutil.copytree(src, dest)

# caminhos absolutos internos -> subpath (ignora protocol-relative "//" e externos)
html_pat = re.compile(r'(href|src|action)="/(?!/)')
# url( absoluto em CSS, com ou sem aspas
css_pat = re.compile(r'url\(["\']?/(?!/)', re.IGNORECASE)

n_html = 0
n_css = 0
for root, dirs, files in os.walk(dest):
    for fn in files:
        p = os.path.join(root, fn)
        if fn.endswith('.html'):
            h = open(p, encoding='utf-8').read()
            h2 = html_pat.sub(lambda m: '%s="/%s/' % (m.group(1), site), h)
            if h2 != h:
                open(p, 'w', encoding='utf-8').write(h2)
                n_html += 1
        elif fn.endswith('.css'):
            c = open(p, encoding='utf-8').read()
            c2 = css_pat.sub(lambda m: 'url(/%s/' % site, c)
            if c2 != c:
                open(p, 'w', encoding='utf-8').write(c2)
                n_css += 1

print('preview: temp.prowel.com.br/%s/  (%d html, %d css reescritos)' % (site, n_html, n_css))
