#!/usr/bin/env python3


from os.path import join
from filecmp import dircmp
from difflib import unified_diff
from sys import stdout, argv
from datetime import datetime, timezone


os_name = argv[1]
OLD_DIR = argv[2]
NEW_DIR = argv[3]
FILES = []
def diff_files(dcmp):
    for name in dcmp.diff_files:
        FILES.append(join(dcmp.right[len(NEW_DIR):], name))
    for sub_dcmp in dcmp.subdirs.values():
        diff_files(sub_dcmp)


dcmp = dircmp(OLD_DIR, NEW_DIR)
diff_files(dcmp) 

date = datetime.now(timezone.utc).isoformat()
title = f"Nouvelle version de la configuration de {os_name}"
subtitle = f"Différence entre les fichiers de configuration de {os_name}"
print(f"""+++
title = "{title}"
description = "{subtitle}"
date = {date}
updated = {date}
draft = false
template = "blog/page.html"

[taxonomies]
authors = ["Automate"]

[extra]
lead = "{subtitle}."
type = "installe"
+++
""")
for filename in FILES:
    print(f'- mise à jour du fichier {filename} :\n')
    try:
        with open(join(OLD_DIR, filename[1:]), 'r') as ori:
            ori_content = ori.readlines()
        with open(join(NEW_DIR, filename[1:]), 'r') as new:
            new_content = new.readlines()
    except UnicodeDecodeError:
        print('fichier binaire')
    else:
        print('```diff')
        for line in unified_diff(ori_content, new_content, fromfile=filename, tofile=filename):
            print(line.rstrip())
        print('```')