#!/bin/sh
set -e

# Detect if running on a Live system where service start should be skipped
is_live_system() {
    # Check common Live system indicators
    grep -q 'boot=live' /proc/cmdline 2>/dev/null && return 0
    grep -q 'rd.live' /proc/cmdline 2>/dev/null && return 0
    [ -d /run/live ] && return 0
    [ -f /.live-installer ] && return 0
    # Check if running in a container (dracut/systemd-nspawn)
    systemd-detect-virt -c -q 2>/dev/null && return 0
    return 1
}

# Ensure cache directory is created with correct permissions
systemd-tmpfiles --create /usr/lib/tmpfiles.d/himmelblau-policies.conf 2>/dev/null || true

# Ensure private data directory is created with correct permissions
systemd-tmpfiles --create /usr/lib/tmpfiles.d/himmelblaud.conf 2>/dev/null || true

# Remove old service files from /etc/systemd/system/ that were installed by v1.4.x
# These take precedence over the new files in /usr/lib/systemd/system/ and lack
# the LoadCredentialEncrypted directive needed for HSM pin handling.
for OLD_FILE in \
    "/etc/systemd/system/himmelblaud.service" \
    "/etc/systemd/system/himmelblaud-tasks.service" \
    "/etc/systemd/system/gdm3.service.d/override.conf"; do
    if [ -f "$OLD_FILE" ]; then
        echo "Removing old service file: $OLD_FILE"
        rm -f "$OLD_FILE"
    fi
done

# Reload systemd to pick up the new service files from /usr/lib/systemd/system/
if command -v systemctl >/dev/null 2>&1; then
    systemctl daemon-reload || true
fi

# Enable and start Himmelblau daemons if systemd is available
# On Live systems, skip service start - the HSM PIN will be generated at first boot
# via the himmelblau-hsm-pin-init.service oneshot when deployed to real hardware.
if command -v systemctl >/dev/null 2>&1; then
    if is_live_system; then
        echo "Live system detected - skipping service start (HSM PIN will be initialized at first boot)"
        # Only enable services so they start on first real boot
        systemctl enable himmelblaud.service himmelblaud-tasks.service 2>/dev/null || true
        # Enable HSM PIN init service separately (may not exist on older systemd)
        systemctl enable himmelblau-hsm-pin-init.service 2>/dev/null || true
    else
        echo "Enabling and starting Himmelblau services..."
        systemctl enable himmelblaud.service himmelblaud-tasks.service 2>/dev/null || true
        # Enable HSM PIN init service separately (may not exist on older systemd)
        systemctl enable himmelblau-hsm-pin-init.service 2>/dev/null || true
        systemctl restart himmelblaud.service himmelblaud-tasks.service 2>/dev/null || true
    fi
fi
