#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
#
# systemd generator (at boot and with systemctl daemon-reload): a timer bashclub-zsync@<name>.timer for each
# configuration /etc/bashclub/<name>.conf with trigger=systemd. Without trigger=systemd nothing is generated
# (cron and autorun stay as they are). Settings of the configuration:
#   schedule   cron format, several separated by ";" (e.g. "*/15 6-22 * * 1-5;0 23 * * *"), default @daily
#   run_as     user of the run, default root
#   log_file   append the output to this file, default the journal
# Activate changes with: bashclub-zsync-timer sync

lib=${ZSYNC_LIB:-/usr/lib/bashclub-zsync/schedule.sh}
conf_dir=${ZSYNC_CONF_DIR:-/etc/bashclub}
out=${1:-/run/systemd/generator}
. "$lib" || exit 0

function warn() {
    # stderr of a generator goes to the kernel log / journal
    echo "bashclub-zsync-generator: $*" >&2
}

for conf in "$conf_dir"/*.conf; do
    [[ -f $conf ]] || continue
    [[ $(conf_trigger "$conf") == "systemd" ]] || continue
    name=$(basename "$conf" .conf)
    if ! valid_name "$name"; then
        warn "$conf: name not usable for a unit (letters, digits, _ . -), no timer"; continue
    fi
    schedule=$(conf_value "$conf" schedule)
    if ! calendars=$(schedule_calendars "${schedule:-@daily}"); then
        warn "$conf: schedule '$schedule' is not a cron schedule (5 fields or @hourly/@daily/...), no timer"; continue
    fi
    run_as=$(conf_value "$conf" run_as)
    log_file=$(conf_value "$conf" log_file)
    # both go into the unit: only a user name and a plain absolute path
    if [[ -n $run_as ]] && ! valid_user "$run_as"; then
        warn "$conf: run_as '$run_as' is not a user name, no timer"; continue
    fi
    if [[ -n $log_file ]] && ! valid_path "$log_file"; then
        warn "$conf: log_file '$log_file' is not a plain absolute path, no timer"; continue
    fi

    mkdir -p "$out/bashclub-zsync@$name.timer.d" "$out/bashclub-zsync@$name.service.d" "$out/timers.target.wants"
    {
        echo "# generated by bashclub-zsync-generator from $conf"
        echo "[Timer]"
        echo "OnCalendar="
        while read -r calendar; do echo "OnCalendar=$calendar"; done <<< "$calendars"
    } > "$out/bashclub-zsync@$name.timer.d/50-schedule.conf"
    {
        echo "# generated by bashclub-zsync-generator from $conf"
        echo "[Service]"
        if [[ -n $run_as && $run_as != "root" ]]; then echo "User=$run_as"; fi
        if [[ -n $log_file ]]; then
            echo "StandardOutput=append:$log_file"
            echo "StandardError=inherit"
        fi
    } > "$out/bashclub-zsync@$name.service.d/50-config.conf"
    ln -sf /usr/lib/systemd/system/bashclub-zsync@.timer "$out/timers.target.wants/bashclub-zsync@$name.timer"
done
exit 0
