#!/usr/bin/env bash
set -euo pipefail

SELF_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=/usr/local/libexec/brixcli/common.sh
source "${SELF_DIR%/bin}/libexec/brixcli/common.sh"

usage() {
  cat <<'EOF'
Usage:
  create-broadcast-job <job-name> <OnCalendar> <command>

Examples:
  create-broadcast-job repo-sync '*-*-* 03:00:00' 'git -C ~/repo pull --ff-only || true'
  create-broadcast-job daily-task 'daily' '~/bin/maintenance.sh'
EOF
}

main() {
  require_root
  load_config
  ensure_runtime_dirs

  local job="${1:-}"
  local oncalendar="${2:-}"
  local command_string="${3:-}"

  [[ -n "${job}" && -n "${oncalendar}" && -n "${command_string}" ]] || { usage; exit 1; }
  validate_job_name "${job}"

  printf '%s\n' "${command_string}" >"${BROADCAST_DIR}/${job}.command"
  chmod 0644 "${BROADCAST_DIR}/${job}.command"

  cat >"/etc/systemd/system/brixcli-broadcast-${job}.timer" <<EOF
[Unit]
Description=BRIX CLI broadcast timer: ${job}

[Timer]
OnCalendar=${oncalendar}
Persistent=true
Unit=brixcli-broadcast@${job}.service

[Install]
WantedBy=timers.target
EOF

  systemctl daemon-reload
  systemctl enable --now "brixcli-broadcast-${job}.timer"

  cat <<EOF
Created broadcast job: ${job}
Schedule: ${oncalendar}
Command:  ${command_string}

Timer unit:   brixcli-broadcast-${job}.timer
Service unit: brixcli-broadcast@${job}.service
EOF
}

main "$@"
