#!/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 = "AfuBarcamp.odp"
WEB_ROOT = "/content/www/dj3ei.famsik.de/2026-AfuBarcamp-Vortrag"

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. 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,
    "index.html",
    "main.css",  # needed by index.html
    ".htaccess",
    ZIP_FILE
]

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

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