#!/usr/bin/env python3

import os
import subprocess
import xml.etree.ElementTree as ET
import datetime
import re

"""
Create an index.html file with the latest 10 commits to the Scribus trunk.

By default the list only shows the basic commit data.
Clicking on the number of changed files, shows the list of affected files.

The script can be customized with the following environment variables:

- SVN_HTML_TARGET: the HTML file to be created (by default './index.html').
- SVN_EXECUTABLE: the svn executable (by default 'svn')
- SVN_SCRIBUS_REPOSITORY: the path to the Scribus code (by default the current directory)

"""

# svn_executable = '/home/ale/bin/tmp/t/usr/bin/svn'
# scribus_repository = '/tmp/scribus'

HTML_TARGET = os.environ.get('SVN_HTML_TARGET', 'index.html')
SVN_EXECUTABLE = os.environ.get('SVN_EXECUTABLE', 'svn')
SCRIBUS_REPOSITORY = os.environ.get('SVN_SCRIBUS_REPOSITORY', '.')

def main():
    print(f'Creating {HTML_TARGET} from {SCRIBUS_REPOSITORY}')
    process = subprocess.run([SVN_EXECUTABLE, 'log', '-l', '10', '--xml', '-v'], cwd=SCRIBUS_REPOSITORY, capture_output=True)
    root_log = ET.fromstring(process.stdout)
    log_output = """
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <title>Scribus | Latest commits</title>
        <style>
        p.commit {margin-bottom: 0px;}
        p.paths {margin-top: 0px; margin-bottom: 0px;}
        ul {margin-top: 0px;}
        ul.hidden {display: none;}
        </style>
        <script>
        document.addEventListener("DOMContentLoaded", function(){
          for (let p of document.getElementsByClassName('paths') ) {
            p.onclick = function() {
              this.nextElementSibling.classList.toggle('hidden');
            }
          }
        });
        </script>
      </head>
      <body>
      <h1>Scribus SVN Log</h1>
      <p>Due to the excessive load generated by rogue web crawlers, it's currently not possible to self-host a web view of the Scribus code.<br>
      This log summarizes the latest commits to the Scribus SVN server (<kbd>svn://scribus.net/trunk/Scribus</kbd>).</p>
      <hr>
    """
    for child_logentry in root_log:
        revision = child_logentry.get('revision')
        author = child_logentry.find('author').text
        date = datetime.datetime.fromisoformat(re.sub(r'\.\d+Z$', 'Z', child_logentry.find('date').text))
        message = child_logentry.find('msg').text.strip()
        commit = f'<p class="commit">{revision} | {author} | {date}\n{message}</p>'
        paths = []
        for child_path in child_logentry.find('paths'):
            paths.append(child_path.text)
        if paths:
            commit += f'\n<p class="paths">{len(paths)} file(s) changed »</p>\n<ul class="hidden">\n<li>{"</li>\n<li>".join(paths)}</li>\n</ul>'
        log_output += commit
    log_output += """
      </body>
    </html>
    """
    with open(HTML_TARGET, 'w') as f:
      f.write(log_output)

if __name__ == '__main__':
    main()
