#!/usr/bin/python3

import shutil
import sys
from pathlib import Path

from sphinx.application import Sphinx
from sphinx.search import languages

if len(sys.argv) != 2:
    sys.exit(f"Usage: {sys.argv[0]} <target-directory>")

here = Path(__file__).parent
static = here / "tmp" / "_static"
out = Path(sys.argv[1])

app = Sphinx(
    srcdir=here,
    confdir=here,
    outdir=here / "tmp",
    doctreedir=here / "tmp" / ".doctrees",
    buildername="html",
)

for language in languages:
    app.config.html_search_language = language

    builder = app.builder
    builder.init()
    builder.prepare_writing(docnames=set())
    builder.copy_static_files()

    if language == "en":
        shutil.copy(static / "language_data.js", out)
        shutil.copy(static / "sidebar.js", out)
    else:
        shutil.copy(static / "language_data.js", out / f"language_data_{language}.js")

shutil.rmtree(here / "tmp")
