#!/usr/bin/env python3


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


os_name = argv[1]
OLD_DIR = argv[2]
NEW_DIR = argv[3]
WEBSITE = len(argv) != 5

def diff_files(dcmp):
    files = []
    for name in dcmp.diff_files:
        files.append(join(dcmp.right[len(NEW_DIR):], name))
    for sub_dcmp in dcmp.subdirs.values():
        files.extend(diff_files(sub_dcmp))
    return files


dcmp = dircmp(OLD_DIR, NEW_DIR)

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}"
if WEBSITE:
    print(f"""+++
title = "{title}"
description = "{subtitle}"
date = {date}
updated = {date}
draft = false
template = "blog/page.html"

[taxonomies]
authors = ["Automate"]

[extra]
lead = "{subtitle}."
type = "installe"
+++""")
    TITLE = True
else:
    TITLE = False


for filename in diff_files(dcmp):
    if not TITLE:
        print(title)
        print("=" * len(title))
        print()
        TITLE = True
    print(f'\n- 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:
        if WEBSITE:
            print('```diff')
        for line in unified_diff(ori_content, new_content, fromfile=filename, tofile=filename):
            print(line.rstrip())
        if WEBSITE:
            print('```')


old = set()
new = set()
for rootname, set_ in ((OLD_DIR, old), (NEW_DIR, new)):
    len_rootname = len(rootname) + 1
    for dirname, _, filenames in walk(rootname):
         for filename in filenames:
             set_.add(join(dirname[len_rootname:], filename))


for filename in old - new:
    print(f'\n- fichier {filename} supprimé.\n')


for filename in new - old:
    if islink(join(NEW_DIR, filename)):
        print(f'\n- lien {filename} ajouté\n')
    else:
        print(f'\n- fichier {filename} ajouté :\n')
        with open(join(NEW_DIR, filename), 'r') as fh:
            if WEBSITE:
                print('```')
            print(fh.read())
            if WEBSITE:
                print('```')