summary: Test journal.persistent core config option

details: |
  In Ubuntu Core systems journal.persistent core config option can be used to
  enable and disable the journal persistence. If persistent journals were previously
  enabled by this setting, changing the value to false will delete all saved logs.

  This test verifies that when journal.persistent core config is set to true, the
  journal logs are written and those are deleted when the config is set to false.

prepare: |
    systemctl status snapd > before.txt

restore: |
    # disable persistent journal
    rm -rf /var/log/journal
    systemctl kill --signal=SIGUSR1 systemd-journald

debug: |
    "$TESTSTOOLS"/journal-state get-log -u snapd
    echo "snapd status before the test:"
    cat before.txt || true
    echo "snapd status after the test:"
    systemctl status snapd || true

execute: |
    echo "Wait for first boot to be done"
    snap wait system seed.loaded

    echo "Precondition check, persistent journal is not available by default"
    not test -e /var/log/journal

    echo "Check that persistent journal can be enabled"
    snap set core journal.persistent=true
    test -e /var/log/journal/
    test -e /var/log/journal/.snapd-created

    # on core16 journald is not reloaded, so changes are not visible until
    # rebooted.
    if not os.query is-core16; then
        # this check relies on *anything* getting logged; enabling persistent
        # journal writes an entry about journal size, which should be sufficient.
        MACHINE_ID=$(cat /etc/machine-id)
        retry -n30 --wait 1 test -e "/var/log/journal/$MACHINE_ID"
    fi

    echo "Check that persistent journal can be disabled"
    snap set core journal.persistent=false
    not test -e /var/log/journal

    echo "Check that journal log is not removed if managed manually"
    mkdir /var/log/journal
    snap set core journal.persistent=true
    not test -e /var/log/journal/.snapd-created

    # NOTE: Since this is failing early, before we do anything to the journal, there is no need to use retry.
    snap set core journal.persistent=false 2>&1 | MATCH "the /var/log/journal directory was not created by snapd"
    # the journal dir was not removed
    test -e /var/log/journal/
    not test -e /var/log/journal/.snapd-created
