#!/usr/bin/python3

"""Perform privileged stillOS setup that must run once on the first boot."""

import fcntl
import os
import shutil
import sys


STATE_DIR = "/var/lib/quick-setup"
COMPLETION_MARKER = os.path.join(STATE_DIR, "first-boot-ran")
LOCK_PATH = "/run/quick-setup-first-boot.lock"

SOURCE_DIR = "/usr/share/quick-setup/bundled-swai"
SWAI_SOURCE = os.path.join(SOURCE_DIR, "io-stillhq-forums.swai")
ICON_SOURCE = os.path.join(SOURCE_DIR, "io-stillhq-forums.png")
SKEL_ZSHRC = "/etc/skel/.zshrc"
ROOT_ZSHRC = "/root/.zshrc"

SWAI_DEST = "/usr/local/share/swai/apps/io.stillhq.forums.swai"
ICON_DEST = (
    "/usr/local/share/icons/hicolor/scalable/apps/"
    "io.stillhq.swai.io.stillhq.forums.png"
)
DESKTOP_DEST = (
    "/usr/local/share/applications/"
    "io.stillhq.swai.io.stillhq.forums.desktop"
)

DESKTOP_CONTENT = """[Desktop Entry]
Version=1.0
Type=Application
Name=stillOS Forums
Exec=/bin/swai "/usr/local/share/swai/apps/io.stillhq.forums.swai"
Terminal=false
StartupWMClass=io.stillhq.swai.io.stillhq.forums
Icon=/usr/local/share/icons/hicolor/scalable/apps/io.stillhq.swai.io.stillhq.forums.png
Categories=Network;
Comment=The official stillOS community forums
Keywords=stillOS;stillHQ;forum;community;support;
"""


def install_file(source, destination, mode):
    os.makedirs(os.path.dirname(destination), mode=0o755, exist_ok=True)
    temporary = destination + ".tmp"
    shutil.copyfile(source, temporary)
    os.chmod(temporary, mode)
    os.replace(temporary, destination)


def main():
    if os.geteuid() != 0:
        print("First-boot setup must run as root.", file=sys.stderr)
        return 1

    if os.path.isfile(COMPLETION_MARKER):
        return 0

    with open(LOCK_PATH, "w", encoding="utf-8") as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)

        # Another invocation may have completed while this one waited.
        if os.path.isfile(COMPLETION_MARKER):
            return 0

        if not os.path.isfile(SWAI_SOURCE) or not os.path.isfile(ICON_SOURCE):
            print("Bundled Forums assets are missing.", file=sys.stderr)
            return 1
        if not os.path.isfile(SKEL_ZSHRC):
            print(f"Skeleton zsh configuration is missing: {SKEL_ZSHRC}", file=sys.stderr)
            return 1

        install_file(SWAI_SOURCE, SWAI_DEST, 0o644)
        install_file(ICON_SOURCE, ICON_DEST, 0o644)
        install_file(SKEL_ZSHRC, ROOT_ZSHRC, 0o644)

        os.makedirs(os.path.dirname(DESKTOP_DEST), mode=0o755, exist_ok=True)
        temporary = DESKTOP_DEST + ".tmp"
        with open(temporary, "w", encoding="utf-8") as desktop:
            desktop.write(DESKTOP_CONTENT)
        os.chmod(temporary, 0o755)
        os.replace(temporary, DESKTOP_DEST)

        os.makedirs(STATE_DIR, mode=0o755, exist_ok=True)
        marker_temporary = COMPLETION_MARKER + ".tmp"
        with open(marker_temporary, "w", encoding="utf-8") as marker:
            marker.write("First-boot setup completed.\n")
        os.chmod(marker_temporary, 0o644)
        os.replace(marker_temporary, COMPLETION_MARKER)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
