#!/bin/bash
# panel-cron get <user>            — print the user's crontab
# panel-cron set <user>            — replace the user's crontab with stdin (syntax-checked, previous version backed up)
# panel-cron run <user>            — run one job now: its command on stdin must be a line of the user's crontab
#                                    (active or paused); output of the first 55 s is printed
# panel-cron on <server> get|set|run <user>   — the same on a connected server
set -euo pipefail
. /opt/panel/bin/panel-lib.sh
act="${1:-}"
if [ "$act" = on ]; then
  srv="${2:-}"; ip=$(node_ip "$srv") || die "unknown server: $srv"; shift 2
  [[ "${1:-}" =~ ^(get|set|run)$ ]] || die "not allowed there: ${1:-}"
  exec timeout 150 ssh "${NODE_SSH_OPTS[@]}" "root@$ip" "/opt/panel/bin/panel-cron $(printf '%q ' "$@")"
fi
u="${2:-}"
valid_user "$u" || die "invalid user: $u"
case "$act" in
  get) crontab -u "$u" -l 2>/dev/null || true ;;
  set)
    tmp=$(mktemp); trap 'rm -f "$tmp"' EXIT
    head -c 200000 > "$tmp"
    mkdir -p /var/lib/panel/cron-backups
    crontab -u "$u" -l > "/var/lib/panel/cron-backups/$u-$(date +%Y%m%d-%H%M%S).txt" 2>/dev/null || true
    ls -1t /var/lib/panel/cron-backups/"$u"-* 2>/dev/null | tail -n +31 | xargs -r rm -f   # keep last 30
    crontab -u "$u" "$tmp" >/dev/null 2>&1 || die "crontab rejected (syntax error) — nothing changed"
    echo "Cron jobs saved for $u"
    ;;
  run)
    IFS= read -r cmd || true
    [ -n "$cmd" ] || die "no command given"
    # only commands that are in the crontab may be started (schedule and a leading # / #moved-to tag are ignored)
    crontab -u "$u" -l 2>/dev/null | sed -E 's/^#moved-to:[a-z0-9-]+ //; s/^#paused-site //; s/^#[[:space:]]*//' \
      | sed -E 's/^(@[a-z]+|([^[:space:]]+[[:space:]]+){5})//' | grep -qxF -- "$cmd" || die "that command is not one of the cron jobs"
    cd "/home/$u" 2>/dev/null || cd /
    set +e
    t=$(mktemp); runuser -u "$u" -- timeout 55 bash -c "$cmd" >"$t" 2>&1 </dev/null; rc=$?
    set -e
    tail -c 6000 "$t"; rm -f "$t"
    case $rc in 0) echo "Finished without errors." ;; 124) echo "Still running after 55 s — stopped here (the scheduled runs are not affected)."; exit 1 ;; *) echo "Ended with exit code $rc."; exit 1 ;; esac
    ;;
  *) die "usage: panel-cron get|set|run <user>";;
esac
