#!/bin/bash

set -e

CONF_FILE="/etc/systemd/journald.conf"

echo "=== Enabling persistent journald logging ==="

echo "Updating $CONF_FILE..."

# Backup once
if [ ! -f "${CONF_FILE}.bak" ]; then
    cp "$CONF_FILE" "${CONF_FILE}.bak"
    echo "Backup created at ${CONF_FILE}.bak"
fi

# Remove existing Storage lines (commented or not)
sed -i '/^Storage=/d' "$CONF_FILE"
sed -i '/^#Storage=/d' "$CONF_FILE"

# Add desired settings under [Journal]
awk '
BEGIN {added=0}
/^\[Journal\]/ {
    print
    print "Storage=persistent"
    added=1
    next
}
{print}
END {
    if (added==0) {
        print "[Journal]"
        print "Storage=persistent"
    }
}
' "$CONF_FILE" > "${CONF_FILE}.tmp"

mv "${CONF_FILE}.tmp" "$CONF_FILE"

# 3. Restart journald
echo "Restarting journald..."
systemctl restart systemd-journald

echo "Done. "
