#! /usr/bin/env python

import os
import subprocess
import re
import sys

FILENAME = 'tmp.html'

if os.path.exists(FILENAME):
    os.unlink(FILENAME)

URL = 'https://namur-preprod.imio.be/fr/@@teleservice-template'
subprocess.call(['wget', '--quiet', '-O', FILENAME, '--convert-links', URL])
content = '{% load i18n static combo %}' + open(FILENAME).read().strip()
if len(content) < 500:
    sys.exit(0)

# replace action of "subscribe newsletter" form
content = content.replace('action="tmp.html"', 'action="https://namur-preprod.imio.be/fr/"')

# remove tmp.html that have been added to anchor links
content = content.replace('tmp.html#', '#')

content = content.replace('</head>',
        '<title>{% firstof global_title "e-Guichet" %} {% block title %}{% endblock %}</title>\n</head>')

content = content.replace('</head>',
        '''
    {% block extra_top_head %}
    {% endblock %}
    {{ media }}
    <link rel="stylesheet" type="text/css" href="{{site_base}}{% static 'site-namur/style.css' %}?{{statics_hash}}">
    {% block extra_css %}
    {% endblock %}
    {% block extra_scripts %}
    {% endblock %}
    </head>''')

content = re.sub('<body(.*?)>',
        r'<body\1 {% block bodyargs %}{% endblock %}>',
        content)

content = content.replace('<div id="teleservice-nav"></div>',
          '<div id="teleservice-nav"><div id="nav">{% block nav %}{% block menu %}{% endblock %}{% endblock %}</div></div>')


content = content.replace('<div id="teleservice-content"></div>',
          '<div id="teleservice-content"><div id="content">{% block content %}{% endblock %}</div></div>')


#content = re.sub(r'<div id="teleservice-nav">.*</div>',
#          '<div id="nav">{% block nav %}{% block menu %}{% endblock %}{% endblock %}</div>',
#          content, flags=re.DOTALL)

#content = re.sub(r'<div id="teleservice-content">.*</div>',
#          '<div id="content">{% block content %}{% endblock %}</div>',
#          content, flags=re.DOTALL)



#content = re.sub(r'<article id="content">.*</article>',
#        '<div id="nav">{% block nav %}{% block menu %}{% endblock %}{% endblock %}</div>'
#        '<div id="content">{% block content %}{% endblock %}</div>',
#        content, flags=re.DOTALL)
#
#content = re.sub(r'<p class="hiddenStructure">Outils personnels</p>(.*?</ul>)',
#        '{% block user-info %} {% endblock %}',
#        content, flags=re.DOTALL)

open('theme.html', 'w').write(content)

