#!/bin/bash

# Install (or refresh) the single daily crontab entry that drives application
# backups. The entry runs `libreportal backup scheduled`, which enqueues a
# backup task per enabled app for the processor to drain serially.
crontabSetupBackupScheduler()
{
    local ISCRON=$( (runAsManager crontab -l) 2>/dev/null )

    if [[ "$ISCRON" == *"command not found"* ]]; then
        isNotice "Crontab is not found. Unable to set up the backup scheduler."
        return 0
    fi

    if ! runAsManager crontab -l 2>/dev/null | grep -q "cron is set up for $sudo_user_name"; then
        isNotice "Crontab is not set up, skipping backup scheduler until it's found."
        return 0
    fi

    local marker="# CRONTAB BACKUP SCHEDULER"
    local scheduler_entry="$CFG_BACKUP_CRONTAB_APP libreportal backup scheduled $marker"

    # Drop any previous scheduler entry, then re-add the current one so a
    # changed schedule (CFG_BACKUP_CRONTAB_APP) always takes effect.
    local result=$(runAsManager crontab -l 2>/dev/null | grep -v "$marker" | runAsManager crontab -)
    local result=$( (runAsManager crontab -l 2>/dev/null; echo "$scheduler_entry") | runAsManager crontab - )
    checkSuccess "Installing the daily backup scheduler entry"

    local schedule_time=$(echo "$CFG_BACKUP_CRONTAB_APP" | cut -d' ' -f2)
    isSuccessful "Enabled apps will be queued for backup daily at ${schedule_time}:00"
}
