#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 10 21:24:31 2022
Modified 2022/02/10
@author: nicolas
@author jean-michel
"""

from pathlib import Path

#USER = "jmbruneau"
USER = "manager"
SAE = "S106"
#SERVER = "https://linserv-info-03.campus.unice.fr"
SERVER = "http://iut.uca.netspace.fr"
#INDEX = f"/home/{USER}/www/{SAE}/index.html"
INDEX = f"/home/{USER}/b1t/{SAE}/index.html"
TITLE = f"SAÉ {SAE} - Sites web"
TEMPLATE = """
<!DOCTYPE html>
<html lang="fr">
	<head>
		<title>{TITLE}</title>
		<meta charset="utf-8" />
	</head>
	<body>
		<h1>{TITLE}</h1>
		<ul>
			{LIST}
		</ul>
	</body>
</html>
"""

print("Creating index.html...")
data = []
for path in Path(f"/home/manager/b1t/{SAE}").glob("*"):
    path_authors = path / f"auteurs.txt"
    login = path.name
    # Students identifiers end with digits.
    if login[2:].isdigit():
        authors = []
        try:
            with open(path_authors) as f:
               for line in f:
                   line = line.strip()
                   if line:
                       authors.append(line)
            data.append((login, authors))
        except IOError:
            pass


def generate_li(login, students):
    return (f"\t\t\t<li><a href='{SERVER}/b1t/{SAE}/{login}'"
            f" target='_blank'>Web site</a> of {', '.join(sorted(students))}</li>")


if __name__ == "__main__":
    Path(INDEX).parent.mkdir(parents=True, exist_ok=True)
    with open(INDEX, "w") as index:
        li_nodes = [generate_li(login, students) for login, students in data]
        LIST="\n".join(li_nodes)
        index.write(TEMPLATE.format(**locals()))
    print("OK")
