###############################################################################
# PROJECT NAME CONFIGURATION
###############################################################################
# Name: fluffy-pancake
#
# IMPORTANT: Change "finpilot" above to your desired project name.
# This name should be used consistently throughout the repository in:
#   - Justfile: export image_name := env("IMAGE_NAME", "your-name-here")
#   - README.md: # your-name-here (title)
#   - artifacthub-repo.yml: repositoryID: your-name-here
#   - custom/ujust/README.md: localhost/your-name-here:stable (in bootc switch example)
#
# The project name defined here is the single source of truth for your
# custom image's identity. When changing it, update all references above
# to maintain consistency.
###############################################################################

###############################################################################
# MULTI-STAGE BUILD ARCHITECTURE (Cache-Isolierung)
###############################################################################
# Isolierte Kontext-Stage NUR für die Build-Skripte.
# Änderungen an /configs oder /scripts hebeln dadurch die DNF-Layer (1-5) NICHT mehr aus!
FROM scratch AS build-ctx
COPY build /build

###############################################################################
# BASE IMAGE
###############################################################################
# labwc/Noctalia-Zweig: minimale fedora-bootc-Basis statt Kinoite.
# Der komplette Desktop (labwc, greetd, Noctalia) wird in den Layern unten
# aufgebaut. Der Kinoite-Stand bleibt auf Branch main / Tag :stable erhalten.
FROM quay.io/fedora/fedora-bootc:44

### /opt (Unverändert)
# RUN rm /opt && mkdir /opt

###############################################################################
# EXECUTION STAGE (Aufgeteilt in Cache-Layer)
###############################################################################

# LAYER 1: Repositories einrichten (Ändert sich fast nie)
RUN --mount=type=bind,from=build-ctx,source=/build/10-repos.sh,target=/tmp/10-repos.sh \
    --mount=type=cache,dst=/var/cache \
    --mount=type=cache,dst=/var/log \
    --mount=type=tmpfs,dst=/tmp \
    bash /tmp/10-repos.sh && dnf5 clean all

# LAYER 2: Unerwünschte Pakete entfernen (Guard - auf bootc-Basis meist No-Op)
RUN --mount=type=bind,from=build-ctx,source=/build/20-remove-packages.sh,target=/tmp/20-remove-packages.sh \
    --mount=type=cache,dst=/var/cache \
    --mount=type=cache,dst=/var/log \
    --mount=type=tmpfs,dst=/tmp \
    bash /tmp/20-remove-packages.sh

# LAYER 2b: labwc Desktop-Basis (Compositor, Portale, Audio, Docking-Tools)
RUN --mount=type=bind,from=build-ctx,source=/build/20-desktop-labwc.sh,target=/tmp/20-desktop-labwc.sh \
    --mount=type=cache,dst=/var/cache \
    --mount=type=cache,dst=/var/log \
    --mount=type=tmpfs,dst=/tmp \
    bash /tmp/20-desktop-labwc.sh

# LAYER 2c: Login-Stack (greetd + tuigreet-Fallback + Noctalia-Greeter)
RUN --mount=type=bind,from=build-ctx,source=/build/21-greetd.sh,target=/tmp/21-greetd.sh \
    --mount=type=cache,dst=/var/cache \
    --mount=type=cache,dst=/var/log \
    --mount=type=tmpfs,dst=/tmp \
    bash /tmp/21-greetd.sh

# LAYER 2d: Noctalia Shell v5 (nativ, aus Fedora-Repos)
RUN --mount=type=bind,from=build-ctx,source=/build/22-noctalia.sh,target=/tmp/22-noctalia.sh \
    --mount=type=cache,dst=/var/cache \
    --mount=type=cache,dst=/var/log \
    --mount=type=tmpfs,dst=/tmp \
    bash /tmp/22-noctalia.sh

# LAYER 2e: Plymouth Bootsplash (Text-Theme + Initramfs-Rebuild)
RUN --mount=type=bind,from=build-ctx,source=/build/23-plymouth.sh,target=/tmp/23-plymouth.sh \
    --mount=type=bind,from=build-ctx,source=/build/plymouth-theme,target=/tmp/plymouth-theme \
    --mount=type=cache,dst=/var/cache \
    --mount=type=cache,dst=/var/log \
    --mount=type=tmpfs,dst=/tmp \
    bash /tmp/23-plymouth.sh

# LAYER 3: Virtualisierung & Tools (Großer Download - stark gecacht)
RUN --mount=type=bind,from=build-ctx,source=/build/30-virt.sh,target=/tmp/30-virt.sh \
    --mount=type=cache,dst=/var/cache \
    --mount=type=cache,dst=/var/log \
    --mount=type=tmpfs,dst=/tmp \
    bash /tmp/30-virt.sh

# LAYER 4: Multimedia Stack (Großer Download - stark gecacht)
RUN --mount=type=bind,from=build-ctx,source=/build/40-multimedia.sh,target=/tmp/40-multimedia.sh \
    --mount=type=cache,dst=/var/cache \
    --mount=type=cache,dst=/var/log \
    --mount=type=tmpfs,dst=/tmp \
    bash /tmp/40-multimedia.sh

# LAYER 5: Flatpak Vorbereitung (Winzig, ganz unten)
RUN --mount=type=bind,from=build-ctx,source=/build/50-prepare-flatpak-for-bazaar.sh,target=/tmp/50-prepare-flatpak-for-bazaar.sh \
    --mount=type=tmpfs,dst=/tmp \
    bash /tmp/50-prepare-flatpak-for-bazaar.sh

###############################################################################
# CONFIGURATION LAYER (Der "saubere" Teil)
###############################################################################

# 1. Kopiere die Filesystem-Fixes (tmpfiles.d, Vendor-Default)
COPY configs/bootc-fix.conf /usr/lib/tmpfiles.d/bootc-fix.conf

# 1b. Container-Policy & Registry Auth für bootc
# sigstoreSigned-Pflicht für eigenes Image, Public-Registries explizit erlaubt
COPY configs/containers/policy.json /etc/containers/policy.json
COPY cosign.pub /etc/pki/containers/cosign.pub
COPY configs/auth.json /etc/containers/auth.json
COPY configs/humocs-man.yaml /etc/containers/registries.d/humocs-man.yaml

RUN chmod 0644 /etc/containers/policy.json /etc/pki/containers/cosign.pub && \
    chmod 0600 /etc/containers/auth.json && \
    python3 -m json.tool /etc/containers/policy.json > /dev/null && \
    python3 -m json.tool /etc/containers/auth.json > /dev/null

# 2. Kopiere die Systemd-Overrides als Vendor-Drop-ins (kein /etc/-Override im Image)
COPY configs/bootc-timer-override.conf /usr/lib/systemd/system/bootc-fetch-apply-updates.timer.d/override.conf
COPY configs/bootc-override.conf /usr/lib/systemd/system/bootc-fetch-apply-updates.service.d/override.conf
COPY configs/remount-fs-ostree-skip.conf /usr/lib/systemd/system/systemd-remount-fs.service.d/skip-on-ostree.conf

# 2b. Kernel-Args (Bootsplash: rhgb quiet)
COPY configs/kargs-plymouth.toml /usr/lib/bootc/kargs.d/plymouth.toml

# 3. Kopiere die Session-Helfer und Desktop-Defaults
COPY --chmod=755 scripts/notify-bootc-user.sh /usr/bin/
COPY --chmod=755 scripts/kanshi-autoconfig /usr/bin/kanshi-autoconfig
COPY --chmod=755 scripts/seed-labwc-skel.sh /usr/bin/seed-labwc-skel
COPY --chmod=755 scripts/bing-wallpaper.sh /usr/bin/bing-wallpaper.sh
COPY --chmod=755 scripts/bing-wallpaper-toggle.sh /usr/bin/bing-wallpaper-toggle.sh

# Desktop-Datei fuer den Toggle (Noctalia-Launcher findet ihn als App)
COPY configs/applications/bing-wallpaper-toggle.desktop /usr/share/applications/bing-wallpaper-toggle.desktop

# User-Units (Bing-Wallpaper-Timer; Enable weiter unten via --global)
COPY configs/systemd/user/bing-wallpaper.service /usr/lib/systemd/user/bing-wallpaper.service
COPY configs/systemd/user/bing-wallpaper.timer /usr/lib/systemd/user/bing-wallpaper.timer

# labwc/kanshi-Defaults fuer neue Benutzer (Bestand bleibt via seed-labwc-skel)
COPY configs/skel/ /etc/skel/

# Wayland-Session fuer Display-Manager (Greeter-Auswahl)
COPY configs/wayland-sessions/labwc.desktop /usr/share/wayland-sessions/labwc.desktop

# Fontconfig-Defaults (Noto statt DejaVu)
COPY configs/fontconfig/60-fluffy-noto.conf /usr/share/fontconfig/conf.d/60-fluffy-noto.conf

# greetd-Konfiguration (Noctalia-Greeter + tuigreet-Fallback dokumentiert)
COPY configs/greetd/config.toml /etc/greetd/config.toml

# Noctalia-Greeter Standardwerte (de-Tastatur etc., werden per tmpfiles
# beim Erst-Boot nach /var/lib/noctalia-greeter/greeter.toml kopiert)
COPY configs/noctalia-greeter/greeter.toml.default /usr/share/noctalia-greeter/greeter.toml.default
COPY configs/tmpfiles/noctalia-greeter-seed.conf /usr/lib/tmpfiles.d/noctalia-greeter-seed.conf

# Fail-fast + Selbstheilung: Der Session-Wrapper-Pfad wird aus dem real
# installierten Paket aufgeloest und in die greetd-Config uebernommen.
# (Terra paketiert eigenstaendig, z.B. /usr/sbin statt /usr/bin.)
# Fehlt Wrapper, D-Bus, polkit oder Session -> Build-Abbruch statt
# defektem Login-Screen.
RUN set -u; \
    id greeter >/dev/null || { echo "FEHLER: Service-User greeter fehlt (21-greetd.sh pruefen)"; exit 1; }; \
    grep -q 'pam_gnome_keyring\.so' /etc/pam.d/greetd || { echo "FEHLER: Keyring-PAM in /etc/pam.d/greetd fehlt"; exit 1; }; \
    test -f /usr/lib64/security/pam_gnome_keyring.so || { echo "FEHLER: pam_gnome_keyring.so fehlt (Paket gnome-keyring-pam?)"; exit 1; }; \
    wrapper="$(command -v noctalia-greeter-session || true)"; \
    echo "Gefundener Wrapper: ${wrapper}"; \
    test -n "${wrapper}" || { echo "FEHLER: noctalia-greeter-session nicht installiert (Terra-Repo/includepkgs pruefen)"; exit 1; }; \
    sed -i "s|^command = \".*\"|command = \"${wrapper}\"|" /etc/greetd/config.toml; \
    grep -Eq "^command = \"${wrapper}\"" /etc/greetd/config.toml || { echo "FEHLER: Wrapper-Pfad konnte nicht in /etc/greetd/config.toml uebernommen werden"; exit 1; }; \
    command -v dbus-run-session >/dev/null || { echo "FEHLER: dbus-run-session fehlt"; exit 1; }; \
    test -x /usr/bin/pkexec || { echo "FEHLER: pkexec fehlt"; exit 1; }; \
    test -f /usr/share/wayland-sessions/labwc.desktop || { echo "FEHLER: labwc-Session fehlt"; exit 1; }; \
    echo "Greeter-Check OK (${wrapper})"

# =============================================================================
# SYSTEMD SERVICES (Modern Bootc Architecture)
# =============================================================================

# 4. Kopiere den Systemd-Service für den Erst-Boot von Flatpak
COPY configs/flatpak-preinstall.service /usr/lib/systemd/system/flatpak-preinstall.service

# 5. Aktiviere Services (Presets greifen nicht bei COPY-Dateien)
# HINWEIS: greetd wird bereits in 21-greetd.sh enabled; hier als
# Doku/Netz doppelt abgesichert (idempotent).
RUN systemctl enable \
   # libvirtd.service \
   # virtlogd.service \
    podman.socket \
    bootc-fetch-apply-updates.timer \
    flatpak-preinstall.service \
    greetd.service

# User-Units global enablen (fuer alle Benutzer; danach pro User per
# systemctl --user disable abschaltbar). Muss NACH dem COPY oben stehen.
RUN systemctl --global enable bing-wallpaper.timer

# SELinux-Labels fuer Greeter/Skel/Sessions (Fehler tolerieren, Labels
# werden beim Deployment ggf. erneut gesetzt)
RUN restorecon -Rv /etc/greetd /etc/skel /usr/share/wayland-sessions 2>/dev/null || true

###############################################################################
# FINAL CLEANUP
###############################################################################
# autoremove + Cache-/Temp-Bereinigung (einmalig, am Ende aller Installs)
RUN --mount=type=bind,from=build-ctx,source=/build/99-cleanup.sh,target=/tmp/99-cleanup.sh \
    --mount=type=tmpfs,dst=/tmp \
    bash /tmp/99-cleanup.sh

###############################################################################
# LINTING 
###############################################################################
# Wir validieren das System via bootc container lint
RUN bootc container lint