#!/usr/bin/env python3

import os.path
import subprocess
import sys


def run(cmd: list[str]) -> None:
    print(" ".join(cmd), file=sys.stderr)
    subprocess.run(cmd, check=True)

SLIDES_FILE = "2026-09_Amateurfunk_MINT_Hobby.odp"
WEB_ROOT = "/content/www/dj3ei.famsik.de/2026-MINT_Hobby"

PDF_FILE = f"{SLIDES_FILE.removesuffix('.odp')}.pdf"
ZIP_FILE = f"{SLIDES_FILE.removesuffix('.odp')}.zip"

if os.path.exists(f".~lock.{SLIDES_FILE}#"):
    raise RuntimeError("You're still editing the slides. Close libreoffice!")

run(["git", "commit",
     "--allow-empty", "-am", "Automatic checkin prior to push"])

run(["git", "push"])

git_ls_result = subprocess.run(
    ["git", "ls-tree", "-r", "HEAD", "--name-only", "-z"],
    encoding="UTF-8",
    env={"LANG": "de_DE.UTF-8"},
    stdout=subprocess.PIPE,
    stdin=subprocess.DEVNULL,
    check=True
)

files_to_zip = git_ls_result.stdout.replace("\0", "\n")

print(f"Packing into ZIP:\n{files_to_zip}\n")

if os.path.exists(ZIP_FILE):
    os.remove(ZIP_FILE)

with subprocess.Popen(
        ["zip", ZIP_FILE, "-9", "-@"],
        env={"LANG": "de_DE.UTF-8"},
        stdin=subprocess.PIPE,
        encoding="UTF-8"
) as proc:
    proc.communicate(files_to_zip)
if proc.returncode != 0:
    raise RuntimeError("Could not ZIP.")                            

push_us = [
    SLIDES_FILE,
    # ARTICLE_FILE,
    "index.html",
    "main.css",  # needed by index.html
    ZIP_FILE
]

def add_PDF_to_upload_if_uptodate(lo_file: str, pdf_file: str) -> None:
    if not(os.path.exists(pdf_file)) or \
       os.path.getmtime(pdf_file) <= os.path.getmtime(lo_file):
        run(["ssh", "andreas@ara.famsik.de", "rm", "-f", f"{WEB_ROOT}/{pdf_file}"])
    else:
        push_us.insert(1, pdf_file)

add_PDF_to_upload_if_uptodate(SLIDES_FILE, PDF_FILE)
# add_PDF_to_upload_if_uptodate(ARTICLE_FILE, ARTICLE_PDF_FILE)

run(["rsync", "-zt", "--info=PROGRESS2", *push_us, f"andreas@albatros.famsik.de:{WEB_ROOT}"])
