from pathlib import Path

root = Path("/home/ifgeyab-whales/entrevuearabia.com")

robots = root / "robots.txt"
robots_text = robots.read_text()
robots_lines = []
for line in robots_text.splitlines():
    stripped = line.strip()
    lower = stripped.lower()
    if stripped == "# Sitemap location":
        continue
    if lower == "disallow: /wp-content/plugins/gtranslate/":
        continue
    if lower.startswith("sitemap:"):
        continue
    robots_lines.append(line)
robots_lines.extend(
    [
        "",
        "# Sitemap location",
        "Sitemap: https://entrevuearabia.com/sitemap_index.xml",
    ]
)
robots.write_text("\n".join(robots_lines).rstrip() + "\n")

htaccess = root / ".htaccess"
block = """
# BEGIN ENTREVUE ARABIA PERF
<IfModule mod_mime.c>
    AddType font/woff2 .woff2
    AddType font/woff .woff
    AddType font/ttf .ttf
    AddType font/otf .otf
    AddType image/avif .avif
</IfModule>

<IfModule mod_expires.c>
    ExpiresByType font/woff2 "access plus 1 year"
    ExpiresByType font/woff "access plus 1 year"
    ExpiresByType font/ttf "access plus 1 year"
    ExpiresByType font/otf "access plus 1 year"
    ExpiresByType image/svg+xml "access plus 1 year"
    ExpiresByType image/avif "access plus 1 year"
</IfModule>

<IfModule mod_headers.c>
    <FilesMatch "\\.(woff2?|ttf|otf|svg|webp|avif)$">
        Header set Cache-Control "public, max-age=31536000, immutable"
        Header set X-Content-Type-Options "nosniff"
    </FilesMatch>
</IfModule>
# END ENTREVUE ARABIA PERF
""".strip()

ht_text = htaccess.read_text()
start = "# BEGIN ENTREVUE ARABIA PERF"
end = "# END ENTREVUE ARABIA PERF"
if start in ht_text and end in ht_text:
    pre = ht_text.split(start, 1)[0].rstrip()
    post = ht_text.split(end, 1)[1].lstrip("\n")
    ht_text = pre + "\n\n" + block + "\n\n" + post
else:
    ht_text = ht_text.rstrip() + "\n\n" + block + "\n"
htaccess.write_text(ht_text)

print("SERVER_TUNED=1")
